【发布时间】:2014-07-21 20:22:21
【问题描述】:
关于在 Doctrine 2 中创建一对多单向关系的几个问题:
- 是否需要连接表?
- docs 说“看看这个例子”,但我看到的只是生成的模式。有人介意快速举个例子,这样我就可以正确注释了吗?
【问题讨论】:
-
您可以尝试不使用@JoinTable 注释并报告它是否正常工作吗?
标签: php symfony doctrine-orm
关于在 Doctrine 2 中创建一对多单向关系的几个问题:
【问题讨论】:
标签: php symfony doctrine-orm
您使用的是 2.0.x 版本的文档。检查this one。你会有例子。
所以是的,您可以避免在两个类之一中使用注释。
【讨论】:
这展示了一对多的关系,一个用户可以有多个报告,而一个报告只能属于一个用户。
class User
{
// ...
/**
* @OneToMany(targetEntity="Report", mappedBy="user")
*/
protected $reports;
public function __construct()
{
$this->reports = new ArrayCollection();
}
public function addReport(\Namespace\To\Report $report)
{
$this->report[] = $report;
}
public function getReports()
{
return $this->reports;
}
}
和
class Report
{
// ...
/**
* @ManyToOne(targetEntity="User", inversedBy="reports")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
public function setUser(\Namespace\To\User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
}
在这种情况下,要创建报告并将其与用户关联,我们将:
// create a User (or find an existing one)
$user = new User();
// create the Report
$report = new Report();
// add the User to the Report
$report->setUser($user);
// then persist it, etc ...
【讨论】:
不,不是。试试这个:
class Foo
{
public function __construct()
{
$this->bars = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @ORM\OneToMany(targetEntity="My\AwesomeBundle\Entity\Bar", mappedBy="foo")
*/
protected $bars;
}
class Bar
{
/**
* @ORM\ManyToOne(targetEntity="My\AwesomeBundle\Entity\Foo", inversedBy="bars")
*/
protected $foo;
}
【讨论】:
Bars 必须了解Foo。如果不是,那就这样吧,但我希望找到一种方法来实现这一点
这适用于 Doctrine 2 + Zend Framework 2.5,同时获取一对多 http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional
在我的情况下,我必须检索产品及其文档(每个产品至少 5 个文档)
ArrayCollection 本身做得很好。
在查看器中,您只需 foreach 对象 Product,然后再一次 foreach $product->getDoc() 就可以了。
【讨论】:
我参加聚会有点晚了,但我就是这样做的:
<entity name="User" table="users">
<id name="id" type="integer" column="id">
<generator strategy="IDENTITY"/>
</id>
<one-to-many field="children" target-entity="User" mapped-by="father">
</one-to-many>
<many-to-one field="father" target-entity="User" inversed-by="children">
<!-- without this row it doesn't work -->
<join-column name="id" referenced-column-name="id" />
</many-to-one>
</entity>
【讨论】: