我在帐户和用户之间有一对多的关系。我正在为 CRUD 使用奏鸣曲管理员。据我所知,它使用 Symfony 表单来完成工作。我尝试添加这样的字段:
->add('users', 'entity', array(
'class' => 'AcmeDemoBundle:User',
'required' => true,
'multiple' => true,
'expanded' => true
));
我也试过sonata_type_model
->add('users', 'sonata_type_model', array(
'class' => 'AcmeDemoBundle:User',
'required' => true,
'multiple' => true,
'expanded' => true
));
问题是在编辑帐户时(当我编辑用户时,所有内容都会更新),没有任何东西(与关系相关)被保存。我知道我必须更新拥有方(用户方),但我没有成功,因为没有调用“public function addUser($user)”所以我不能添加类似“$user->setAccount($this )" 到那个函数。
我的实体如下所示:
class Account
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\OneToMany(targetEntity="Acme\DemoBundle\User", mappedBy="account", cascade={"persist", "remove"})
*/
protected $users;
/**
* Add users
*
* @param Acme\DemoBundle\Entity\User $user
* @return Account
*/
public function addUser(\Acme\DemoBundle\Entity\User $user)
{
$user->setAccount($this);
$this->users[] = $user;
return $this;
}
/**
* Remove users
*
* @param Acme\DemoBundle\Entity\User $user
*/
public function removeUser(\Acme\DemoBundle\Entity\User $user)
{
$user->setAccount(null);
$this->users->removeElement($user);
}
/**
* Get users
*
* @return Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
.
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Acme\DemoBundle\Account", inversedBy="users")
*/
protected $account;
/**
* Set account
*
* @param Acme\DemoBundle\Entity\Account $account
* @return User
*/
public function setAccount(\Acme\DemoBundle\Entity\Account $account = null)
{
$this->account = $account;
return $this;
}
/**
* Get account
*
* @return Acme\DemoBundle\Entity\Account
*/
public function getAccount()
{
return $this->account;
}
}