Doctrine学习笔记(实体ManyToMany) —— 4

Many-To-Many, Unidirectional¶

——–单向的

用户实体和Book实体, 多对多关系

class User

    /**
     * @var
     *
     *
     * @ORM\ManyToMany(targetEntity="Book")
     * @ORM\JoinTable(name="t_users_books",
     *      joinColumns={@ORM\JoinColumn(name="t_user_id", referencedColumnName="t_id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="t_book_id", referencedColumnName="b_id")}
     *      )
     *
     * 
     */
    private $books;

class Book

这种单项的关系,在另外的实体类里不要写上属性, 

/**
     * @var
     * @ORM\ManyToOne(targetEntity="Author", inversedBy="books")
     * @ORM\JoinColumn(name="author_id", referencedColumnName="a_id")
     */
    private $author;

    //这里我在Book实体中把User注释了
    // private $users;


    public function __construct()
    {
        $this->users = new ArrayCollection();
        $this->categories = new ArrayCollection();
    }

这时候实体类已经设计好了, 执行验证, 测试是否正确

php app\console  doctrine:schema:validate

如果控制台报

[Mapping]  OK - The mapping files are correct.
[Database] FAIL - The database schema is not in sync with the current mapping file.

继续执行更新实体类, 设置set get 方法,

php app\console generate:doctrine:entities HelloBundle

然后你再执行php app\console doctrine:schema:validate 验证时, 成功通过

F:\Zend\workspaces\my_project_name>f:\Zend\\workspaces\php-v\php app\console doctrine:schema:update --force
Updating database schema...
Database schema updated successfully! "12" queries were executed

即可执行更新实体类到数据库

php app\console doctrine:schema:update --force

Many-To-Many, Bidirectional

–双向关系

class User

    /**
     * @ManyToMany(targetEntity="Book", inversedBy="users")
     * @JoinTable(name="t_users_books")
     */
    private $books;

    public function __construct() {
        $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
    }

class Book

    /**
     * @ManyToMany(targetEntity="User", mappedBy="books")
     */
    private $users;

    public function __construct() {
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
    }

这时候实体设计完成, 在执行php app\console doctrine:schema:validate验证时, 报错

The referenced column name 'id' has to be a primary key column on the target entity class 'MyFirst\HelloBundle\Entity\User'.

原因是双向关系(多对多)在生成第三方关系表时, 不能成功设置外键,

解决方案 请采用第一种


form godruoyi supper

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值