【问题标题】:Symfony2 Self referencing many to many relationSymfony2 自引用多对多关系
【发布时间】:2013-11-13 21:24:25
【问题描述】:

我是 symfony2 的新手,我很难理解表单。

这个话题之前已经讨论过,但主要是关于关系方面的。我在表单以及如何管理关系的保存方面遇到问题。 场景是一个用户有很多朋友都是用户。所以是一个自引用的多对多关系。

我正在使用 FOSUser Bundle 并拥有一个友谊实体。这是用于创建实体的 YAML。

MH\FriendshipBundle\Entity\Friendship:
type: entity
table: mh_friendship
repositoryClass: MH\FriendshipBundle\Entity\FriendshipRepository
id:
    id:
        type: integer
        generator:
            strategy: AUTO
fields:
    requested_at:
        type: datetime
        gedmo:
            timestampable:
                on: create
    is_accepted:
        type: boolean
        nullable: true
    accepted_at:
        type: datetime
        nullable: true
manyToOne:
    user:
        targetEntity: MH\UserBundle\Entity\User
        inversedBy: user_friends
        joinColumn:
            name: user_id
            referencedColumnName: id
    friend:
        targetEntity: MH\UserBundle\Entity\User
        inversedBy: friend_users
        joinColumn:
            name: friend_id
            referencedColumnName: id
lifecycleCallbacks:
    prePersist:   [ ]
    postPersist:  [ ]
    preUpdate:    [ ]
    postUpdate:   [ ]


MH\UserBundle\Entity\User:
type:  entity
table: mh_user
repositoryClass: MH\UserBundle\Entity\UserRepository
id:
    id:
        type: integer
        generator:
            strategy: AUTO
fields:
    first_name:
        type: string
        length: 100
        nullable: true
    last_name:
        type: string
        length: 100
        nullable: true
    created_at:
        type: datetime
        gedmo:
            timestampable:
                on: create
    updated_at:
        type: datetime
        gedmo:
            timestampable:
                on: update
oneToMany:
    user_friends:
        targetEntity: MH\FriendshipBundle\Entity\Friendship
        mappedBy: user
        cascade: ["persist", "remove"]
    friend_users:
        targetEntity: MH\FriendshipBundle\Entity\Friendship
        mappedBy: friend
        cascade: ["persist", "remove"]
    friend_groups:
        targetEntity: MH\FriendshipBundle\Entity\FriendGroup
        mappedBy: owner
        cascade: ["persist", "remove"]
lifecycleCallbacks:
    prePersist:   [ ]
    postPersist:  [ ]
    preUpdate:    [ ]
    postUpdate:   [ ]

现在我有一个通过友谊资源中的 crud 生成器创建的表单,这就是我正在做的事情。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('friend', 'entity', array(
                            'class' => 'UserBundle:User',
                            'property' => 'fullName',
                            'expanded' => true,
                            'multiple' => true,
                            'required' => false,
                    ))
    ;

}

它呈现了一个用户复选框列表,我可以选择并保存为“朋友”。

我的问题是:

  1. 保存时出现以下错误。

PHP Catchable 致命错误:传递给 MH\FriendshipBundle\Entity\Friendship::setFriend() 的参数 1 必须是 MH\UserBundle\Entity\User 的实例,给定的 Doctrine\Common\Collections\ArrayCollection 的实例,调用/Users/mohammedhamad/Sites/socialbills/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php 在第 345 行并在 /Users/mohammedhamad/Sites/sociabills/src/MH/FriendshipBundle/Entity/Friendship 中定义.php 第 155 行,引用者:http://sociabills.local/friends/new

不确定如何确保将选择的“朋友”传递给需要集合的 setFriends 方法,而不是需要用户对象的 setUser 方法。

  1. 如何让表单列出所有其他用户,登录用户除外。不希望一个人成为自己的朋友。

【问题讨论】:

  • 我确定我知道问题 1 的答案,但它现在回避了我……考虑一下。至于问题 2,您可以在 entity 字段类型中使用 query_builder 选项 - 您可能需要手动将当前用户的引用或他们的 id 传递给 buildForm。您应该可以通过 $options 参数来做到这一点。如果我能连贯地回答这两个问题,我会发布答案..

标签: php forms symfony doctrine


【解决方案1】:

查看文档

/**
 * @ManyToMany(targetEntity="User", mappedBy="myFriends")
 **/
private $friendsWithMe;

/**
 * @ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
 * @JoinTable(name="friends",
 *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")}
 *      )
 **/
private $myFriends;

public function __construct() {
    $this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
    $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}

// ...

}

注释的 YML 等效项是(请记住,我不习惯 yml 进行实体映射,并且未经过测试)

   manyToMany:
     myFriends:
       targetEntity: User
       inversedBy: friendsWithMe
       joinTable:
         name: friends
         joinColumns:
           user_id:
             referencedColumnName: id
         inverseJoinColumns:
           friends_user_id:
             referencedColumnName: id
     friendsWithMe:
       targetEntity: User
       mappedBy: myFriends

然后你可以在你的类中实现addMyFriend($friend)方法和removeMyFriend($friend)

public function addMyFriend($friend){

 $this->myFriends[] = $friend;

}

public function removeMyFriend($friend)
{
    $this->myFriends->removeElement($friend);
}

@Darragh 回答了问题 2

【讨论】:

  • 我不确定我想在这里建立多对多的关系。我需要能够拥有额外的字段(requested_at、is_accepted、accepted_at)来跟踪关系。我认为表单类型应该是数据类 User,并且用户类需要能够处理传递给它的用户对象并通过 addUserFriend 方法设置该信息。唯一的问题是 addUserFriend 只接受 Friendship 实体。在这种情况下使用数据转换器将用户转换为友谊对象是否正确?
【解决方案2】:

问题 1:

我确定您已从错误中注意到,第一个问题之所以出现,是因为 setFriend() 需要一个 User 实体,但却收到一个或多个 User 实体的 ArrayCollection

这是表单组件的创建者 Bernhard Schussek 的discussed here in a blog post。我假设您使用的版本 >= 2.1?如果是这样,您需要添加一些额外的方法:

public function addFriend(User $friend)
{
    $this->friend[] = $friend;
}

和:

public function removeFriend(User $friend)
{
    $this->friends->removeElement($friend);
}

我的理解是,ArrayCollection 中的每个元素都会调用这些方法。我正在我的一个存储库中查看一个类似的示例,这就是在我的一个实体中实现的。

这在 >= 2.1 版本中可用。

问题 2:

要使用自定义选项填充表单entity 元素,您可以使用query_builder 选项。我的代码库中的快速剪切和粘贴示例:

->add('client', 'entity', array(
    'class'         => 'HooluxDAPPUserBundle:Organisation',
    'property'      => 'name',
    'query_builder' => function(EntityRepository $er) use ($builder) {
        if ($builder->getData()->hasAdvertiser()) {
            return $er->buildQueryClientsForAdvertiser(
                $builder->getData()->getAdvertiser()
            );
        }
        return $er->createQueryBuilder('c');
    }
))

query_builder 选项接受一个匿名函数/闭包,该函数/闭包接收对您的实体的存储库类的引用。您可以调用任何返回查询构建器对象的自定义方法。

编辑

在您的控制器中:

// pass current user's own id as an option 
$this->createForm(new FriendType(), $entity, array('user_id' => $this->getUser()));

buildForm 方法中:

public function buildForm($builder, $options) {
    $builder
        ->add('friend', 'entity', array(
            'class' => 'UserBundle:User',
            'property' => 'fullName',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            // closure, include $options from parent scope with `use`
            'query_builder' => function(EntityRepository $er) use ($options) {
                // current user's own id
                $userId = $options['user_id'];
                // call custom method on UserRepository class
                return $er->getUsersWhereIdIsNot($userId); // returns QueryBuilder object

            }
        ));
}

然后添加一个返回所有用户WHERE id != :id 或其他任何内容的方法。

希望这会有所帮助:)

【讨论】:

  • 开始尝试使用查询生成器,但由于某种原因,我无法将变量传递给public function newAction() { $user = $this->getUser(); $entity = new Friendship(); $form = $this->createCreateForm($entity, array('user'=>$user)); return $this->render('MHFriendshipBundle:Friendship:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); }
  • 当我将用户传递给表单时,我不断得到一个未定义的索引。似乎无法访问它。
  • 嗨。当您使用Controller::createForm() 方法时,第一个参数是表单对象的实例,第二个是表单表示的实体 - 第三个(可选)参数是您可以传递给buildForm() 的选项数组方法。在您发布的示例中,您缺少作为参数#2 的实体(我假设它是用户实体)
  • 我想通了。我基本上在表单中添加了一个受保护的 $user,并添加了构造函数来传递和设置用户对象。在控制器中,当我实例化表单时,我通过 $form = $this->createForm(new FriendshipType($user), 。奇迹般有效。我如何弄清楚收藏的全部保存情况。
  • 酷,祝你好运!
猜你喜欢
  • 1970-01-01
  • 2018-08-19
  • 2017-02-05
  • 1970-01-01
  • 2018-10-02
  • 2017-03-23
相关资源
最近更新 更多