问题描述
我在处理多对多关系时遇到了一些麻烦.我有 Users
和 Assets
.我希望能够将用户分配到资产页面上的资产.
I am having some trouble with a many to many relationship. I have Users
and Assets
. I would like to be able to assign users to an asset on the asset page.
下面的代码在创建/编辑资产时显示用户列表,但是对用户复选框所做的更改不会保存,而其余数据会保留.
The code below displays a list of users when creating/editing an asset, however changes made to the user checkboxes do not save, while the rest of the data is persisted.
如果我通过 mysql 客户端向 users_assets 添加一个条目,这些更改会显示在资产列表中.
If I add an entry to users_assets through the mysql client, these changes are shown in the asset list.
用户
class User extends BaseUser
{
/**
* @ORMManyToMany(targetEntity="Asset", inversedBy="users")
*/
private $assets;
}
资产
class Asset
{
/**
* @ORMManyToMany(targetEntity="User", mappedBy="assets")
*/
private $users;
}
资产类型
public function buildForm(FormBuilderInterface $builder, array $options)
{
$form = $builder
->add('users', null, array(
'expanded' => true,
'multiple' => true
))
->getForm();
return $form;
}
推荐答案
出于某种原因,我不得不切换学说映射以使其正常工作:
For some reason I had to switch the doctrine mappings to get this to work:
Asset:
/**
* @ORMManyToMany(targetEntity="AdaptiveUserBundleEntityUser", inversedBy="assets")
* @ORMJoinTable(name="user_assets")
*/
private $users;
User:
/**
* @ORMManyToMany(targetEntity="SplashSiteBundleEntityAsset", mappedBy="users")
*/
private $assets;
现在,当我保存资产时,它会保存关联的用户.我不需要将 builder->add 定义为实体或集合.我只是将它传递给 null,它使用映射信息来填充实体信息:
Now when I save the asset it saves the users associated. I did not need to define builder->add as an entity or collection. I simply pass it null and it uses the mapping info to fill in the entity info:
AssetType:
->add('users', null, array('expanded' => "true", "multiple" => "true"))
不完全确定为什么我需要在 Asset vs The User 上拥有 inversedBy 和 JoinTable 信息,但它现在似乎可以工作了!
Not exactly sure why I needed to have the inversedBy and JoinTable info on the Asset vs The User but it seems to be working now!
感谢您的建议!!!
这篇关于Symfony2 Doctrine2 多对多形式不保存实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!