首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Symfony2 跨 Bundle 實體關聯:不同 Bundle 間一對多關係映射實戰

     編輯:PHP 相關知識

核心結論

跨 Bundle 實體關聯與同 Bundle 內完全一致,關鍵只需在映射配置中寫明完整的實體命名空間路徑。

場景示例

  • UserBundle:CommentOne 實體(多方)
  • AdminBundle:ShopOne 實體(一方)

映射配置實戰

多方實體:UserBundle/Entity/CommentOne.php

// Annotation 方式
/**
 * @ORM\ManyToOne(targetEntity="AdminBundle\Entity\ShopOne", inversedBy="comments")
 * @ORM\JoinColumn(name="shop_id", referencedColumnName="id")
 */
protected $shop;

一方實體:AdminBundle/Entity/ShopOne.php

/**
 * @ORM\OneToMany(targetEntity="UserBundle\Entity\CommentOne", mappedBy="shop")
 */
protected $comments;

public function __construct() {
    $this->comments = new ArrayCollection();
}

Controller 中使用

$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,關聯生效

避坑指南

  1. 命名空間拼寫:targetEntity 必須精確到 Bundle 名稱(區分大小寫)
  2. 自動加載:確保 composer.json PSR-4 配置正確,php app/console doctrine:schema:validate 無報錯
  3. 生成 Getter/Setter:執行 php app/console doctrine:generate:entities 同步代碼
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved