Php Symfony 3:如何使用条令同步用户
我想知道如何同步用户,例如在我的用户表(fos_user)上,我想将用户名与其他表同步 因此,如果我想知道谁是发表评论的用户,我想做的就是这样做 $commentA->getUser() 它将显示用户表的用户(fos_user),当用户更改其用户名时,注释将获得其新用户名Php Symfony 3:如何使用条令同步用户,php,symfony,doctrine,Php,Symfony,Doctrine,我想知道如何同步用户,例如在我的用户表(fos_user)上,我想将用户名与其他表同步 因此,如果我想知道谁是发表评论的用户,我想做的就是这样做 $commentA->getUser() 它将显示用户表的用户(fos_user),当用户更改其用户名时,注释将获得其新用户名 感谢您的帮助您正在寻找的是数据库关系-原则中的一对一/多对一-请参阅文档中的- 然后您使用主键作为连接键,而不是用户名。我想您需要这样的东西 在用户类中,您需要此属性和方法: /** * Class User * @ORM
感谢您的帮助您正在寻找的是数据库关系-原则中的一对一/多对一-请参阅文档中的-
然后您使用主键作为连接键,而不是用户名。我想您需要这样的东西 在
用户
类中,您需要此属性
和方法
:
/**
* Class User
* @ORM\Table(name="`user`")
*/
class User extends FosUser
{
[Your other properties]
/**
* @var Collection
*
* @ORM\OneToMany(targetEntity="Comment", mappedBy="user")
*/
protected $comments;
/**
* User constructor.
*/
public function __construct()
{
parent::__construct();
$this->comments = new ArrayCollection();
}
/**
* @return Collection
*/
public function getComments(): Collection
{
return $this->comments;
}
/**
* @param Comment $comment
*/
public function addComment(Comment $comment): void
{
if ($this->getComments()->contains($comment)) {
return;
} else {
$this->getComments()->add($comment);
$comment->setUser($this);
}
}
/**
* @param Comment $comment
*/
public function removeComment(Comment $comment): void
{
if (!$this->getComments()->contains($comment)) {
return;
} else {
$this->getComments()->removeComment($comment);
$comment->setUser(null);
}
}
}
在您的注释
类中,您需要此属性
和方法
:
/**
* Class User
* @ORM\Table(name="`comment`")
*/
class Comment
{
[Your other properties]
/**
* @var User
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="comments")
*/
protected $user;
/**
* @return User
*/
public function getUser(): User
{
return $this->user;
}
/**
* @param User $user
*/
public function setUser(User $user): void
{
/** Maybe you need this too, if get exception delete this line */
$user->addComment($this);
$this->user = $user;
}
}
也许您需要在用户类或注释类中的注释中使用cascade={“persist”}
。。。取决于你的逻辑
类似于这条线的东西
* @ORM\OneToMany(targetEntity="Comment", mappedBy="user", cascade{"persist"})
现在,您的注释已连接到所有者用户,如果用户发生更改,请也提交用户更改,并且您必须以如下方式使用类用户:
$comment->getUser()->getUsername();