我正在建立一个博客网站,用户可以在其中发布包含许多类别的博客文章。我想在每个单独的博客下面显示推荐的博客文章。推荐的博客文章应该基于与你正在看的博客文章具有相同的类别。
我第一次在SQL查询,它的工作,但当我试图在它实现我的项目使用createQueryBuilder我得到所有的博客文章在网站上,而不是只是那些包含相同的类别。
下面是我的SQL查询:
SELECT
*
FROM
blog b
INNER JOIN
blog_category bc ON b.id = bc.blog_id
INNER JOIN
category c ON bc.category_id = c.id
WHERE
c.id IN (SELECT
c.id
FROM
blog b
INNER JOIN
blog_category bc ON b.id = bc.blog_id
INNER JOIN
category c ON bc.category_id = c.id
WHERE
b.id = 33) and b.id != 33 group by b.id
正如我所说,这个查询工作得很好,但当我试图在我的Symfony项目中使用它时,它不工作。
public function findRelatedBlogs($blog_Id)
{
$qbCat = $this->_em->createQueryBuilder();
$qbCat->select('ca.id')
->from('AppBundle:Blog', 'bl')
->join('bl.categories', 'ca')
->where('b.id =:blogid')
->setParameter('blogid', $blog_Id);
$qb = $this->_em->createQueryBuilder();
$qb->select('b')
->from('AppBundle:Blog', 'b')
->join('b.categories', 'c')
->where($qb->expr()->in('c.id', $qbCat->getDQL()))
->where('b.id !=:blogid')
->groupBy('b.id')
->setParameter('blogid', $blog_Id);
return $qb->getQuery()->getResult();
}
我好像找不到哪里不对。
好的,我让它工作了伙计们原来我在subselect查询中犯了一个错别字
$qbCat = $this->_em->createQueryBuilder();
$qbCat->select('ca.id')
->from('AppBundle:Blog', 'bl')
->join('bl.categories', 'ca')
->where('bl.id =:blogid')
->setParameter('blogid', $blog_Id);
"->"行,其中('b。id =:看")错误,应该是bl.id =:blogid。由于我犯了这个错误,它无法找到id .
谢谢大家的帮助:)