Doctrine 2:在引用表中使用额外列处理多到多列的最佳方法我想知道什么是最好的,最干净的,最简单的方式来处理多到多的关系在原则2。假设我们有一张专辑木偶大师金属有几个脚印。但请注意,一首歌可能会出现在更多的专辑中,比如电池金属有三张专辑都是以这首歌为特色的。所以我需要的是专辑和曲目之间的多对多的关系,使用第三个表和一些额外的列(比如在指定相册中的曲目位置)。实际上,正如Doctrine的文档所建议的那样,我必须使用一对多的双重关系来实现这一功能。/** @Entity() */class Album {
/** @Id @Column(type="integer") */
protected $id;
/** @Column() */
protected $title;
/** @OneToMany(targetEntity="AlbumTrackReference", mappedBy="album") */
protected $tracklist;
public function __construct() {
$this->tracklist = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getTitle() {
return $this->title;
}
public function getTracklist() {
return $this->tracklist->toArray();
}}/** @Entity() */class Track {
/** @Id @Column(type="integer") */
protected $id;
/** @Column() */
protected $title;
/** @Column(type="time") */
protected $duration;
/** @OneToMany(targetEntity="AlbumTrackReference", mappedBy="track") */
protected $albumsFeaturingThisTrack; // btw: any idea how to name this relation? :)
public function getTitle() {
return $this->title;
}
public function getDuration() {
return $this->duration;
}}/** @Entity() */class AlbumTrackReference {
/** @Id @Column(type="integer") */
protected $id;
/** @ManyToOne(targetEntity="Album", inversedBy="tracklist") */
protected $album;
/** @ManyToOne(targetEntity="Track", inversedBy="albumsFeaturingThisTrack") */
protected $track;
/** @Column(type="integer") */
protected $position;
/** @Column(type="boolean") */
protected $isPromoted;
public function getPosition() {
return $this->position;
}
public function isPromoted() {
return $this->isPromoted;
}
public function getAlbum() {
return $this->album;
}
public function getTrack() {
return $this->track;
}}
3 回答
![?](http://img1.sycdn.imooc.com/54586425000103f602200220-100-100.jpg)
收到一只叮咚
TA贡献1821条经验 获得超4个赞
class AlbumTrackReference { public function getTitle() { return $this->getTrack()->getTitle() }}
$album->getTracklist()[12]->getTitle()
$track->getAlbums()[1]->getTitle()
getTitle()
getTracklist() { foreach ($this->tracklist as $trackRef) { $trackRef->setContext($this); } } // .... getAlbums() { foreach ($this->tracklist as $trackRef) { $trackRef->setContext($this); } } // ... AlbumTrackRef::getTitle() { return $this->{$this->context}->getTitle(); }
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
慕姐8265434
TA贡献1813条经验 获得超2个赞
class AlbumTrackReference{ public function getTitle() { return $this->getTrack()->getTitle(); } public function getDuration() { return $this->getTrack()->getDuration(); }}
foreach ($album->getTracklist() as $track) { echo sprintf("\t#%d - %-20s (%s) %s\n", $track->getPosition(), $track->getTitle(), $track->getDuration()->format('H:i:s'), $track->isPromoted() ? ' - PROMOTED!' : '' );}
- 3 回答
- 0 关注
- 468 浏览
添加回答
举报
0/150
提交
取消