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
相关文章推荐
- 一个关于if else容易迷惑的问题
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- php7 读取php.ini[4]
- PHP+Apache在Windows 9x下的安装和配置
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站
- PHP 5.3.0 安装分析心得
- apache 环境下 php 的配置注意事项
- ASP.NET、ASP、PHP、JSP之间有什么区别?
- PHP VBS JS 函数 对照表
- C语言实现的统计php代码行数功能源码(支持文件夹、多目录)