主观2自我查询 [英] Doctrine 2 Self Join Query

查看:157
本文介绍了主观2自我查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在还不太了解Doctrine,而我正在尝试检索用户要遵循的建议列表。

I'm still pretty new to Doctrine and I'm trying to retrieve a suggest list of users to follow.

所以基本上,给定一个用户A需要选择用户A遵循的用户遵循的所有用户,不包括用户A已经遵循的用户。

So basically, given an user A, I need to select all users that are followed by the users that user A follow, excluding users that user A already follow.

如何使用Doctrine查询构建器? / p>

How could I do that with Doctrine query builder ?

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解决方案,我试过这个

EDIT: According to slaur4 solution, I tried this

    $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'


推荐答案

这是一个自引用的查询。我会尝试这样:

It's a self-referencing query. I would try this :

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

这篇关于主观2自我查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆