教义中的一对多关系

时间:2013-10-08 05:38:28

标签: php symfony doctrine-orm annotations doctrine

我有2张桌子

  1. 用户
  2. 消息
  3. 表格结构:

    用户:

    enter image description here

    消息:

    enter image description here

    现在看到用户表中有多少用户,他们的消息存储在<{>}消息表中,由fk_user_Id标识。

    如何在这两个表之间建立一对多关系,或使用 Doctrine / Annotations创建此SQL架构?

1 个答案:

答案 0 :(得分:1)

这是一种常见的情况,我认为如果你想搜索的话,你可以轻松找到这样的例子。

您可以参考此example

您的两个实体文件User.phpMessage.php看起来像这样

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $username;

    /**
     * @ORM\OneToMany(targetEntity="Message", mappedBy="user")
     */
    protected $messages;
}

消息实体将如下所示

    /**
     * @ORM\Entity
     * @ORM\Table(name="messages")
     */
    class Message
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;

        /**
         * @ORM\Column(type="string")
         */
        protected $messageDescription;

        /**
         * @ORM\ManyToOne(targetEntity="User", inversedBy="messages")
         * @ORM\JoinColumn(name="fk_user_id", referencedColumnName="id")
         */
        protected $user;
}
相关问题