My problem is simple:
I have Users and Stories in a many to many relationship, I would 开发者_JAVA百科like to store a couple of attribute in the UserStory relationship:
- Priority (In order to set the ordering of the display for a given user)
- Main (flags which one is the main story)
How can I do that ?
Let say we have the following :
<?php
/** @Entity */
class User
{
// ...
/**
* @ManyToMany(targetEntity="Story", inversedBy="users")
* @JoinTable(name="users_stories")
*/
private $stories;
public function __construct() {
$this->stories = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
/** @Entity */
class Story
{
// ...
/**
* @ManyToMany(targetEntity="User", mappedBy="stories")
*/
private $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
?>
As Crozin suggested, this question is a duplicate of:
- Doctrine2: Best way to handle many-to-many with extra columns in reference table
In my specific case the solution is simple. The Many-To-Many relationship needs to be build by hand, and extra fields need to be added manually. So two OneToMany relationship need to be build.
So here are my 3 objects and the associated meta information for each attribute:
<?php
/**
* @Entity
* @Table(name="users")
*/
class User{
/**
* @Id
* @Column(type="integer", name="id")
* @GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @OneToMany(targetEntity="UserStory", mappedBy="user")
*/
private $user_stories;
// ...
}
/**
* @Entity
* @Table(name="user_stories")
*/
class UserStory{
/**
* @Id
* @Column(type="integer", name="id")
* @GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ManyToOne(targetEntity="User", inversedBy="user_stories")
*/
private $user;
/**
* @ManyToOne(targetEntity="Story", inversedBy="user_stories")
*/
private $stories;
/**
* @Column(type="integer")
*/
private $priority;
/**
* @Column(type="integer")
*/
private $priority_tmp;
/**
* @Column(type="integer")
*/
private $main;
// ...
}
/**
* @Entity
* @Table(name="stories")
*/
class Story
{
/**
* @Id
* @Column(type="integer", name="id")
* @GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @OneToMany(targetEntity="UserStory", mappedBy="stories")
*/
private $user_stories;
// ...
}
?>
精彩评论