簡體   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