Doctrine 2 ManyToMany cascade(学说 2 多对多级联)
问题描述
是否可以在 Doctrine 2 中创建两个多对多相关的对象并仅对其中一个调用 persist 来保存两者?
Is it possible in Doctrine 2 to create two objects that are many to many related and call persist only on one of them to save both?
用户实体:
/**
* Owning Side
*
* @ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist"})
* @JoinTable(name="user_roles",
* joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
public $roles;
角色实体:
/**
* Inverse Side
*
* @ManyToMany(targetEntity="User", mappedBy="roles")
*/
public $users;
保存:
$role = new Role();
$user = new User();
$user->roles->add($role);
$role->users->add($user);
$em->persist($user);
$em->flush();
它不起作用并抛出错误通过未配置为级联持久操作的关系找到了新实体:EntitiesRole@0000000004a29c11000000005c48cb75.显式持久化新实体或在关系上配置级联持久化操作."
It doesn't work and trows an error "A new entity was found through a relationship that was not configured to cascade persist operations: EntitiesRole@0000000004a29c11000000005c48cb75. Explicitly persist the new entity or configure cascading persist operations on the relationship."
推荐答案
您应该将 cascade={"persist"}
应用于 Role 实体.
You should apply cascade={"persist"}
to the Role entity.
不是 Doctrine 的专家,但我认为 Doctrine 会检查关联实体的级联选项.
Not an expert on Doctrine, but I think Doctrine checks the associated entity for cascading options.
由于您将持久化from Users 角色,它会检查角色 实体,如果它应该用级联持久化.
Since you are cascading the persist from Users to Roles, it checks the Role entity if it should be persisted with cascade.
这篇关于学说 2 多对多级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:学说 2 多对多级联
基础教程推荐
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01