Reputation: 415
I was wandering if it is possible to make something via doctrine... I'll try to explain: U have an object like a Human being. He/She has its attributes like height, weight etc. Now here we have 2 tables "humans" and "human_attributes". For many to many relationship we have to create the third table "human2human_attributes" which doctrine generates by itself which has the id-s from the tables listed. What i want is to put beside the two id fields a value field, like
id_human id_human_attribute value
2 12 180cm
which translates to Human id-2 has attribute id-12(height) with value 180cm.
Is it possible to do something like this in doctrine and if it is does anybody know how to implement it in Symfony2?
Thanks.
Upvotes: 0
Views: 173
Reputation: 8645
You don't have the choice with doctrine2 if you want to add a third field you can't use a ManyToMany relationship but an intermediate entity :
/**
* @ORM\Entity()
* @ORM\Table(name="human_has_attribute",
* uniqueConstraints = {
* @ORM\UniqueConstraint(name="unique_human_human_attribute", columns={"human_id", "human_attribute_id"})
* }
* )
*/
class HumanHasAttritube
{
// ...
/**
* @var Human
*
* @ORM\ManyToOne(targetEntity="Human", inversedBy="humanHasAttributes")
* @ORM\JoinColumn(name="human_id", referencedColumnName="id")
*/
protected $human;
/**
* @var HumanAttribute
*
* @ORM\ManyToOne(targetEntity="HumanAttribute", inversedBy="humanHasAttributes")
* @ORM\JoinColumn(name="human_attribute_id", referencedColumnName="id")
*/
protected $humanAttribute;
/**
* @var string
*
* @ORM\Column(type="string", length=255)
*/
protected $value;
}
Please note I added a unique SQL constraint thanks to uniqueConstraints parameter of @ORM\Table, that say human and humanAttribute both are unique (if it respects the logic of your system, otherwise remove lines concerning uniqueness, or add also the value field, or what you want ^^) !
Don't forget when validating to add a Unique validator too (if it's unique) :
* @UniqueEntity(
* fields={"human", "humanAttribute"},
* message="A human can't have the same attribute 2 times."
* )
class HumanHasAttribute
Upvotes: 1