我正在尝试添加与组具有多对多关系的新用户,但只有用户保存在数据库中
这是我的用户.php
/**
* AcmeUserBundleEntityUser
*
* @ORMTable(name="User")
* @ORMEntity(repositoryClass="AcmeUserBundleEntityUserRepository")
*/
class User implements AdvancedUserInterface, Serializable
{
/**
* @ORMColumn(name="id", type="integer")
* @ORMId()
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORMColumn(name="username", type="string", length=25, unique=true)
*/
private $username;
/**
* @ORMColumn(name="salt", type="string", length=40)
*/
private $salt;
/**
* @ORMColumn(name="password", type="string", length=40)
*/
private $password;
/**
* @ORMColumn(name="email", type="string", length=60, unique=true)
*/
private $email;
/**
* @ORMColumn(name="isActive", type="boolean")
*/
private $isActive;
/**
* @ORMManyToMany(targetEntity="Group", inversedBy="users")
*
* @ORMJoinTable(name="user_group",
* joinColumns={@ORMJoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORMJoinColumn(name="group_id", referencedColumnName="id")}
* )
*
*/
private $groups;
public function __construct()
{
$this->isActive = true;
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
$this->groups = new ArrayCollection();
}
/**
* @inheritDoc
*/
public function getRoles()
{
$roles = array();
foreach ($this->groups as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
/**
* @see Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $roles field !
*/
return json_encode(array(
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
));
}
/**
* @see Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
) = json_decode($serialized);
}
public function eraseCredentials()
{
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
return $this->salt;
}
public function getPassword()
{
return $this->password;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set salt
*
* @param string $salt
* @return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Set password
*
* @param string $password
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set email
*
* @param string $email
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isActive
*
* @param boolean $isActive
* @return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* @return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Add groups
*
* @param AcmeUserBundleEntityGroup $groups
* @return User
*/
public function addGroup(AcmeUserBundleEntityGroup $groups)
{
$groups->addUser($this);
$this->groups -> add($groups);
return $this->groups;
}
/**
* Remove groups
*
* @param AcmeUserBundleEntityGroup $groups
*/
public function removeGroup(AcmeUserBundleEntityGroup $groups)
{
$this->groups->removeElement($groups);
}
/**
* Get groups
*
* @return DoctrineCommonCollectionsCollection
*/
public function getGroups()
{
return $this->groups;
}
}
我的小组.php
<?php
namespace AcmeUserBundleEntity;
use SymfonyComponentSecurityCoreRoleRoleInterface;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineORMMapping as ORM;
/**
* @ORMTable(name="groups")
* @ORMEntity
*/
class Group implements RoleInterface, Serializable
{
/**
* @ORMColumn(name="id", type="integer")
* @ORMId()
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/** @ORMColumn(name="name", type="string", length=30) */
private $name;
/** @ORMColumn(name="role", type="string", length=20, unique=true) */
private $role;
/** @ORMManyToMany(targetEntity="User", mappedBy="groups",cascade={"persist"}) */
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
// ... getters and setters for each property
/** @see RoleInterface */
public function getRole()
{
return $this->role;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @see Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $users field !
*/
return json_encode(array(
$this->id,
$this->role
));
}
/**
* @see Serializable::unserialize()
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->role
) = json_decode($serialized);
}
/**
* Set name
*
* @param string $name
* @return Group
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set role
*
* @param string $role
* @return Group
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Add users
*
* @param AcmeUserBundleEntityUser $users
* @return Group
*/
public function addUser(AcmeUserBundleEntityUser $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* @param AcmeUserBundleEntityUser $users
*/
public function removeUser(AcmeUserBundleEntityUser $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* @return DoctrineCommonCollectionsCollection
*/
public function getUsers()
{
return $this->users;
}
}
和来自我的控制器的片段
public function newAction(Request $request)
{
$user = new User();
$form = $this->createFormBuilder($user)
->add('username', 'text')
->add('password', 'text')
->add('email', 'email')
->add('submit','submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$user=$form->getData();
$group=new Group();
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$user->setSalt(md5(time()));
$pass = $encoder->encodePassword($form->getData()->getPassword(), $user->getSalt());
$user->setPassword($pass);
$group->setRole('ROLE_USER');
$user->addGroup($group);
$em = $this->getDoctrine()->getManager();
$em->merge($user);
$em->flush();
return $this->redirect($this->generateUrl('login'));
}
return $this->render('AcmeUserBundle:User:new.html.twig', array(
'form' => $form->createView(),
));
在数据库中,我有 3 个表:用户、组和user_group(user_id、group_id)从实体生成的所有内容。我可以注册新用户,但它没有保存在user_group中。
感谢您的任何帮助。
Ps.对不起我的英语不好
据我所知,你没有拯救你的团队。 因此,由于您没有保存它,因此没有要保存user_group,因为您的组不存在于数据库中。 但是,一旦执行此操作,您将遇到另一个问题,因为您对组的角色字段具有唯一的约束,因此一旦您尝试注册多个人,您将收到一个数据库错误,指出您有一个重复项。 您需要从数据库中提取组,而不是每次都创建一个新组。
$group = $this->em->getRepository('Group')->findOneByRole('ROLE_USER');
$user->addGroup($group);
$em->persist($group);
$em->persist($user);
$em->flush();
更新控制器以包含:
$group = $em->getRepository('AcmeUserBundle:Group')->findOne(array('role' => 'ROLE_USER'));
$user->addGroup($group);
$em->persist($user);
$em->persist($group);
$em->flush();
您忘记在代码中保留 Group 实体,因此它没有保存任何数据。
顺便说一下,我建议使用处理所有这些逻辑的用户服务,而不是将它们全部放在控制器中。
此外,在您的用户.php中,您可以只执行以下操作:
/**
* @ORMManyToMany(targetEntity="Group", inversedBy="user")
*/
protected $groups;
不需要@JoinColumn注释。如果未指定,则从表和主键名称推断属性名称和引用列名称。