我有一个选择查询,我正在尝试添加一个连接。
在下面的示例中,我有一个Question
实体用于返回一些结果,我想添加User
实体的连接,如:
SELECT question FROM question AS q LEFT JOIN USER u ON q.user_id= u.id;
我希望结果是User
实体中的Question
实体,例如:
private Question (entity)
private id
private user_id
private User (entity)
private id
private name
这是我的班级
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Question;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
class QuestionRepository extends EntityRepository
{
/**
* @param int $currentPage
*
* @return Paginator
*/
public function getQuestions($currentPage = 1)
{
$questions = $this->createQueryBuilder('question')
->where('question.active is NULL')
->getQuery();
$paginator = $this->paginate($questions, $currentPage);
return $paginator;
}
}
我称之为
$questionRepo = $this->container->get('doctrine')->getManager()->getRepository('AppBundle:Question');
$questions = $questionRepo->getQuestions(1);
有什么想法吗?
答案 0 :(得分:0)
怎么样:
$questions = $this->createQueryBuilder('question')
->leftJoin('question.user', 'question_user', 'WITH', 'question_user.user = :user_id')
->where('question.active is NULL')
->setParameter('user_id', $user_id)
->getQuery();
$paginator = $this->paginate($questions, $currentPage);
修改:由于您的最新评论,我必须提一下,此建议假设您的Question
实体看起来像这样(根据User
的实体:
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="question")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
如果没有,请添加此项,生成实体(php app/console doctrine:generate:entities AppBundle:Question
)并更新数据库(php app/console doctrine:schema:update --force
)。
PS:在生成实体之前,您必须删除旧的getter / setter。