App\Bundle\Resources\config\doctrine\User.orgm.yml
AppBundleEntityUser:
type: entity
table: Users
// ...
manyToMany:
groups:
targetEntity: Group
inversedBy: users
joinTable:
name: Users_relate_Groups
joinColumns:
user_id:
onDelete : CASCADE
referencedColumnName: id
inverseJoinColumns:
group_id:
onDelete : CASCADE
referencedColumnName: id
应用程序\捆绑包\资源\配置\原则\Group.orgm.yml
AppBundleEntityGroup:
type: entity
table: Groups
// ...
manyToMany:
users:
cascade : ["persist"]
mappedBy : groups
targetEntity: User
App\Bundle\Entity\User.php
use FOSUserBundleModelUser as BaseUser;
class User extends BaseUser
{
protected $groups;
public function __construct()
{
parent::__construct();
$this->groups = new DoctrineCommonCollectionsArrayCollection();
}
// ...
App\Bundle\Entity\Group.php
use FOSUserBundleModelGroup as BaseGroup;
class Group extends BaseGroup
{
protected $users;
public function __construct($name, $roles = array())
{
parent::__construct($name, $roles);
$this->users = new DoctrineCommonCollectionsArrayCollection();
}
public function addUser(AppBundleEntityUser $users)
{
if (!$this->getUsers()->contains($users)) {
$this->getUsers()->add($users);
}
return $this;
}
public function getUsers()
{
return $this->users;
}
// ...
现在,这个条件。
这确实是正确的
将向用户添加一个组。
$user->addGroup($group);
$userManager->updateUser($user);
但这行不通
用户未添加到组中。
$group->addUser($this->getUser());
$groupManager->updateGroup($group);
无法从组对象中添加用户。
通常,add函数也需要调用反面的相应标记。类似的解决方案还有另一个答案
这实际上有点棘手,因为它需要双向工作。我认为递归不会有问题,因为第三个调用将被跳过,因为用户已经包含了组。
public function addUser(AppBundleEntityUser $users)
{
if (!$this->getUsers()->contains($users)) {
$this->getUsers()->add($users);
$users->addGroup($this);
}
return $this;
}
所以按顺序:
- 您调用Group->addUser
- 组调用用户->addGroup
- 用户(可能)调用Group->addUser
- 由于Group已经拥有该用户,因此它结束
也许有一个更好的解决方案,但它至少应该起作用。