简体   繁体   中英

Association mapping in Doctrine

I have 2 tables: jobs and categories . The first table has a field called cat_id which is a reference to categories . id . In my Entity Class Job I have annotations like this:

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

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

And in my Category Class I have:

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

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

All I want is to get all jobs with their categories and all jobs by category. But I'm still new to Doctrine.

You appear to be overlooking some elements of the owning vs the inverse side of Doctrine relationship mappings. I suggest you read 12. Association Updates: Owning Side and Inverse Side in the Doctrine manual for more details.

Essentially, one side of a 1:N relationship will be the Owning side, and the other the Inverse side. The owning side is the one that actually maps the relationship, while the inverse side simply reflects that mapping. - In your code, you've put the JoinColumn on both sides, as if both are supposed to be the owning side.

Your code should have the Job.category property as the owning side, and the Category.jobs property as the inverse side. So start by changing the Job entity to look more like this:

/**
 * @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.
}

And then change the Category entity to look like this:

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

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

Note that in the Job entity, I've added the inversedBy attribute to the ManyToOne annotation, indicating the Category.jobs property as the inverse side of the mapping. Then I've removed the JoinColumn from the Category.jobs attribute, since the inverse side shouldn't actually specify a mapping directly; it is reflects the mapping of the owning side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM