我对Doctrine还很陌生,我正在尝试检索要关注的用户建议列表。
基本上,鉴于用户A,我需要选择用户A关注的用户所遵循的所有用户,不包括用户A已经关注的用户。
我如何使用Doctrine查询构建器执行此操作?
class User
{
...
/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="followees")
* @ORM\JoinTable(name="user_followers",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn(name="follower_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
private $followers;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="followers")
*/
private $followees;
}
编辑:根据slaur4解决方案,我试过了
$qb = $this->createQueryBuilder('u');
$qb->select('suggestions')
->join('u.followees', 'followees')
->join('followees.followers', 'suggestions')
->where('u.id = :id')
->andWhere($qb->expr()->notIn('suggestions.id', 'u.followees'))
->setParameter('id', $user->getId());
但它给了我以下例外:
QueryException: [Syntax Error] line 0, col 171: Error: Expected Literal, got 'u'
答案 0 :(得分:1)
这是一个自引用查询。我会试试这个:
QueryBuilder(用户Symfony2存储库)
<?php
//Subquery to exclude user A followees from suggestions
$notsQb = $this->createQueryBuilder('user')
->select('followees_excluded.id')
->join('user.followees', 'followees_excluded')
->where('user.id = :id');
$qb = $this->createQueryBuilder('suggestions');
$qb->join('suggestions.followers', 'suggestions_followers')
->join('suggestions_followers.followers', 'users')
->where('users.id = :id')
->andWhere('suggestions.id != :id') //Exclude user A from suggestions
->andWhere($qb->expr()->notIn('suggestions.id', $notsQb->getDql()))
->setParameter('id', $userA->getId());
$query = $qb->getQuery();
$users = $query->getResult(); // array of User