脚本宝典收集整理的这篇文章主要介绍了php – 问题理解关系映射在原则2,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
关键字
id int(11) comment_id int(11) text vArchar(30)
注释
id int(11) text text
这是我如何映射他们:
/** * @EntITy * @Table(name="comments") **/ class Comments { /** @Id @Column(tyPE="integer") */ PRivate $id; /** @Column(type="text") */ private $text; /** * @OneToMany(targetEntity="keywords",mappedBy="comment_id") */ 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; private $text; public function getText(){return $this->text;} public function getId(){return $this->id;} }
以及如何使用它是这样的:
$comments = $this->em->getRepository('comments' )->findAll(); foreach($comments as $comment){ foreach($comment->getKeywords() as $keyword){ $keyword->getText(); } }
并得到这个错误:
Notice: Undefined index: comment_id in C:\web_includes\doctrine\ORM\Persisters\BasicEntityPersister.PHP on line 1096 Notice: Trying to get property of non-object in C:\web_includes\doctrine\ORM\Persisters\BasicEntityPersister.PHP on line 1098 Warning: Invalid argument supplied for foreach() in C:\web_includes\doctrine\ORM\Persisters\BasicEntityPersister.PHP on line 1098 Notice: Undefined index: comment_id in C:\web_includes\doctrine\ORM\PersistentCollection.PHP on line 168 Fatal error: Call to a member function setValue() on a non-object in C:\web_includes\doctrine\ORM\PersistentCollection.PHP on line 169
/** * @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;} }
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,PRIMARY KEY(id)) ENGINE = InnoDB; ALTER TABLE keywords ADD FOReiGN KEY (comment_id) REFERENCES comments(id);
映射中的两个问题:
>你必须了解拥有和反面之间的区别.只需要一对多单向关系就需要第三个连接表.然而,使用双向关系,就像我的映射中拥有的属性Keyword :: $comment一样.
>“mappedBy”是指另一个targetEntity上的属性,即“这个关联的另一面”. InversedBy有一些相同的含义,只是这个inversedBy总是在所有方面指定,mappedBy在反面.
这一切听起来都非常复杂,但它是从ORM技术角度来看非常有效的方法,因为它允许使用最少数量的所需sql UPDATE语句来更新关联.查看有关逆向/拥有如何工作的文档:
以上是脚本宝典为你收集整理的php – 问题理解关系映射在原则2全部内容,希望文章能够帮你解决php – 问题理解关系映射在原则2所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。