您的位置:首页 > 编程语言 > PHP开发

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

2016-04-01 09:50 603 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  doctrine php