The mappedBy attribute does say nothing about the name of the foreign key, That is what the "@JoinColumn" annotation is for. The correct mapping for this scenario would be:
/**
* @Entity
* @Table(name="comments")
**/
class Comments
{
/** @Id @Column(type="integer") */
private $id;
/** @Column(type="text") */
private $text;
/**
* @OneToMany(targetEntity="keywords", mappedBy="comment")
*/
private $keywords;
public function getText(){return $this->text;}
public function getId(){return $this->id;}
public function getKeywords(){return $this->keywords;}
}
/**
* @Entity
* @Table(name="keywords")
*/
class Keywords
{
/** @Id @Column(type="integer") */
private $id;
/**
* @ManyToOne(targetEntity="Comments", inversedBy="keywords")
*/
private $comment;
/**
* @Column(type="text") */
private $text;
public function getText(){return $this->text;}
public function getId(){return $this->id;}
}
Using Schema Tool it generates the SQL which equals your schema:
CREATE TABLE comments (id INT NOT NULL, text LONGTEXT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
CREATE TABLE keywords (id INT NOT NULL, comment_id INT DEFAULT NULL, text LONGTEXT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
ALTER TABLE keywords ADD FOREIGN KEY (comment_id) REFERENCES comments(id);
Two problems in your mapping:
- You have to understand the difference between owning and inverse side. Just having a One-To-Many uni-directional relation requires a third join table. However with a bi-directional relation like in my mapping with the owning side property Keyword::$comment it works.
- "mappedBy" refers to the property on the other targetEntity that is "the other side of this associations". InversedBy has somewhat the same meaning, just that inversedBy is always specified on the owning side, mappedBy on the inverse side.
This all sounds very complicated, but its a very efficient way from the ORMs technical perspective, because it allows to update associations with the least number of required SQL UPDATE statements. See the docs on how Inverse/Owning works:
http://www.doctrine-project.org/projects/orm/2.0/docs/reference/association-mapping/en#owning-side-and-inverse-side
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…