繁体   English   中英

原则 2 - 一对多单向

[英]Doctrine 2 - One-to-Many unidirectional

关于在 Doctrine 2 中创建一对多单向关系的几个问题:

  1. 是否需要连接表?
  2. 文档说“看看这个例子”,但我看到的只是生成的模式。 有人介意举一个简单的例子,这样我就可以得到正确的注释吗?

这演示了一对多关系,用户可以拥有多个报表,一个报表只能属于一个用户。

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 ...

您使用的是2.0.x版本的文档。 检查一下 你将有这个例子。

所以,是的,你可以避免两个类之一的注释。

不,它不是。 试试这个:

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;
}

这适用于Doctrine 2 + Zend Framework 2.5,同时获取一对多http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to -many双向

在我的情况下,我不得不检索产品及其文件(每个产品至少5个文件)

ArrayCollection本身做得很好。

在查看器中,您只需要访问对象Product,然后再次使用$ 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM