问题
I have a many to many table for User
and House
, called user_house
. Instead of just two columns: user_id and house_id, i want to add 3 more: eg action, created_at, updated_at. How can I do this?
I cannot find any relevant docs on this.
The following just creates a separate table with two columns in it.
class User extends EntityBase
{
...
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\House")
*/
protected $action;
Basically, what I want to achieve is:
in the user_house
table the combination of user_id
, house_id
, action
should be unique.
when a user clicks a "view" on a house, user_house table gets updated with some user_id
, some house_id
, view
, now()
, now()
when a user clicks a "like" on a house, user_house table gets updated with some user_id
, some house_id
, like
, now()
, now()
when a user clicks a "request a call" on a house, user_house table gets updated with some user_id
, some house_id
, contact
, now()
, now()
Could someone point me in the right direction? Thanks!
回答1:
You need to break your ManyToMany
relation to OneToMany
and ManyToOne
by introducing a junction entity called as UserHasHouses
, This way you could add multiple columns to your junction table user_house
User Entity
/**
* User
* @ORM\Table(name="user")
* @ORM\Entity
*/
class User
{
/**
* @ORM\OneToMany(targetEntity="NameSpace\YourBundle\Entity\UserHasHouses", mappedBy="users",cascade={"persist","remove"} )
*/
protected $hasHouses;
}
House Entity
/**
* Group
* @ORM\Table(name="house")
* @ORM\Entity
*/
class House
{
/**
* @ORM\OneToMany(targetEntity="NameSpace\YourBundle\Entity\UserHasHouses", mappedBy="houses",cascade={"persist","remove"} )
*/
protected $hasUsers;
}
UserHasHouses Entity
/**
* UserHasHouses
* @ORM\Table(name="user_house")
* @ORM\Entity
*/
class UserHasHouses
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="NameSpace\YourBundle\Entity\House", cascade={"persist"}, fetch="LAZY")
* @ORM\JoinColumn(name="house_id", referencedColumnName="id")
*/
protected $houses;
/**
* @ORM\ManyToOne(targetEntity="NameSpace\YourBundle\Entity\User", cascade={"persist","remove"}, fetch="LAZY" )
* @ORM\JoinColumn(name="user_id", referencedColumnName="id",nullable=true)
*/
protected $users;
/**
* @var \DateTime
* @ORM\Column(name="created_at", type="datetime")
*/
protected $createdAt;
/**
* @var \DateTime
* @ORM\Column(name="updated_at", type="datetime")
*/
protected $updatedAt;
//... add other properties
public function __construct()
{
$this->createdAt= new \DateTime('now');
}
}
have additional column in ManyToMany join table in Doctrine (Symfony2)
来源:https://stackoverflow.com/questions/50344073/symfony-manytomany-table-extra-columns