私はsymfonyを初めて使いました。周りを見回しましたが、私の問題に対する正しい答えが見つかりませんでした。
多対多の関係でリンクされた 2 つのエンティティがあります。エンティティUser
-> エンティティFollowedUser
. 人は何人かをUser
フォローできるべきであり、彼をフォローする人が何人かいるべきFollowedUser
です。FollowedUser
Users
私の問題は、たとえば myFollowedUser
を 1 つにすべてリストしようとすると、 my に関連付けられているものだけでなく、すべてが取得されることです。User
CurrentUser
FollowedUser
CurrentUser
これが私のコードです。
ユーザー エンティティ( src/MyBundle/Entity/User.php
) :
namespace MyBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="My_user")
*/
class User extends BaseUser
// ...
/**
* @var FollowedUser[] $followedUsers
*
* @ORM\ManyToMany(targetEntity="MyBundle\Entity\FollowedUser")
*/
private $followedUsers;
// ...
public function getFollowedUsers()
{
return $this->followedUsers;
}
}
ユーザータイプ:
namespace MyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use MyBundle\Entity\FollowedUserRepository;
class UserType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('followedUsers'); // This shows me the whole table
//,'entity' , array('class' => 'MyBundle\Entity\FollowedUser',
// 'multiple' => true,
// 'query_builder' => function(FollowedUserRepository $followedUserRepo) use ($options) {
// $followedUsers = $options['data']->getFollowedUsers();
// $choices = array();
// foreach ( $followedUsers as $followedUser){
// $choices[] = $followedUser->getId();
// }
// $qb = $followedUserRepo->createQueryBuilder('u');
// $qb->select('u')
// ->where( $qb->expr()->in('u.id',$choices));
// return $qb;
// }
// ));
}
public function getName()
{
return 'followedUser';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'MyBundle\Entity\User',
);
}
}
注意:私がコメントした行は、私がやりたいことをする唯一の方法です。しかし、それを行う正しい方法は感じられません。
私のコントローラーで:
$currentUser = $this->container->get('security.context')->getToken()->getUser();
$followedUsers = $currentUser->getFollowedUsers(); // That works properly
$form = $this->createForm(new UserType(),$currentUser);
編集 :
実際、私の問題は、ManyToMany 宣言で注釈を忘れていたことです。以下は、一方向の ManyToMany 関係に使用する必要があるデフォルトの注釈です。
/**
* @ManyToMany(targetEntity="Group")
* @JoinTable(name="users_groups",
* joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
解決策は、doctrine2 unidirectionnal ManyToManyのドクトリン ドキュメントで見つかりました。