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 多对多级联
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
