簡體   English   中英

Symfony 3:如何使用Doctrine同步用戶

[英]Symfony 3: How to sync users using Doctrine

我想知道如何同步用戶,例如在用戶表(fos_user)上,我想將用戶名與另一個表同步。

所以,如果我想看看誰是發表評論的用戶,我想做

$ commentA->的getUser();

它將顯示用戶表(fos_user)的用戶,為此,當用戶更改其用戶名時,注釋將獲得其新的用戶名。

感謝幫助

你所尋找的是數據庫的關系-一對多/多對一的學說-查看文件- https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one一對多雙向

然后,您將主鍵用作連接鍵,而不是用戶名。

我想你需要這樣的東西

在您的User類中,您需要以下propertymethods

/**
 * 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);
        }
    }
}

Comment類中,您需要以下propertymethods

/**
 * 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;
    }
}

也許您需要在User類或Comment類的批注中使用cascade={"persist"} ,具體取決於您的邏輯。

像這條線

 * @ORM\OneToMany(targetEntity="Comment", mappedBy="user", cascade{"persist"})

現在,您的注釋已連接到所有者用戶,如果用戶更改,也要提交用戶更改,則您必須像這樣使用類用戶:

$comment->getUser()->getUsername();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM