2014-04-03 27 views
2

我有2個表格:jobscategories。第一個表格有一個名爲cat_id的字段,它是對categories的引用。 id。在我的實體類Job我有註釋是這樣的:原則中的關聯映射

/** 
* @ManyToOne(targetEntity="Category") 
* @JoinColumn(name="cat_id", referencedColumnName="id") 
**/ 
private $category; 

public function __construct() 
{ 
    $this->category = new \Doctrine\Common\Collections\ArrayCollection(); 
} 

而在我的類別I類有:

/** 
* @OneToMany(targetEntity="Job", mappedBy="job") 
* @JoinColumn(name="id", referencedColumnName="cat_id") 
*/ 
private $jobs; 

public function __construct() 
{ 
    $this->jobs = new \Doctrine\Common\Collections\ArrayCollection(); 
} 

我想要的是按類別得到與他們的類別中的所有作業和所有作業。但我仍然對新學說感到陌生。

+0

你的實體在這裏是正確的,不是嗎?我想你應該通過在EntityRepository中使用查詢構建器來創建自定義請求。 – Debflav

回答

1

您似乎忽略了擁有一側的Doctrine關係映射。我建議您在Doctrine手冊中閱讀12. Association Updates: Owning Side and Inverse Side瞭解更多詳情。

本質上,的1一側:N關係將是擁有側,而另一側。擁有方是實際映射關係的一方,而反方則僅反映該映射。 - 在你的代碼中,你已經把JoinColumn放在兩邊,好像這兩個都應該是自己的一面。

您的代碼應該有Job.category屬性作爲擁有方,Category.jobs屬性作爲反面。

/** 
* @var Category 
* 
* @ManyToOne(targetEntity="Category", inversedBy="jobs") 
* @JoinColumn(name="cat_id", referencedColumnName="id") 
**/ 
private $category; 

public function __construct() 
{ 
    // $category would be a single instance of Category, 
    // not a collection. Otherwise you'd be looking at a 
    // ManyToMany relationship. 
} 

,然後更改類別實體,看起來像這樣:

/** 
* @var ArrayCollection 
* 
* @OneToMany(targetEntity="Job", mappedBy="category") 
*/ 
private $jobs; 

public function __construct() 
{ 
    $this->jobs = new \Doctrine\Common\Collections\ArrayCollection(); 
} 

注意,在工作單位,我已經添加了所以通過改變工作實體看起來更像這個啓動inversedBy屬性爲ManyToOne註釋,指示Category.jobs屬性作爲映射的反面。然後我從Category.jobs屬性中刪除了JoinColumn,因爲反面不應直接指定映射;它反映了擁有方的映射。

+0

非常感謝。我多次瀏覽了文檔,試圖弄清楚「擁有」或「反面」的含義。現在一切都按照我的想法工作。 :) –