跨 Bundle 實體關聯與同 Bundle 內完全一致,關鍵只需在映射配置中寫明完整的實體命名空間路徑。
CommentOne 實體(多方)ShopOne 實體(一方)// Annotation 方式 /** * @ORM\ManyToOne(targetEntity="AdminBundle\Entity\ShopOne", inversedBy="comments") * @ORM\JoinColumn(name="shop_id", referencedColumnName="id") */ protected $shop;
/**
* @ORM\OneToMany(targetEntity="UserBundle\Entity\CommentOne", mappedBy="shop")
*/
protected $comments;
public function __construct() {
$this->comments = new ArrayCollection();
}
$shop = $em->getRepository('AdminBundle:ShopOne')->find(1);
$comment = new \UserBundle\Entity\CommentOne();
$comment->setShop($shop);
$comment->setContent('跨 Bundle 評論測試');
$em->persist($comment);
$em->flush();
shopone 表:正常存儲主記錄
commentone 表:shop_id 正確寫入對應 ID,關聯生效
targetEntity 必須精確到 Bundle 名稱(區分大小寫)composer.json PSR-4 配置正確,php app/console doctrine:schema:validate 無報錯php app/console doctrine:generate:entities 同步代碼