symfony 需要使用QueryBuilder执行联接查询的帮助

6ss1mwsb  于 2022-11-16  发布在  其他
关注(0)|答案(3)|浏览(144)

我得到了一个有效的SQL查询:select p.name, p.id from acv_project p join acv_product prod on prod.project_id = p.id where prod.weight <> 0 and p.green_user_id = 18
如果我把它传递给一个

$stmt = $em->getConnection()->prepare($rawSql);
        $stmt->execute([]);

        $projects = $stmt->fetchAll();

它可以工作,但我想通过添加“绿色_user_id”作为参数来传递它,而不总是18。
当我尝试使用此代码时:`

$sql2 = "select p from ArtoAcvBundle:Project p join prod ArtoAcvBundle:Product on prod.project_id = p.id where prod.weight <> 0 and p.green_user_id =:userId";
        $query2 = $em->createQuery($sql2)->setParameters(
                array('userId' => $userId));
        
        $projects = $query2->getResult();

我得到[Semantical Error] line 0, col 48 near 'ArtoAcvBundle:Product': Error: Identification Variable prod used in join path expression but was not defined before.
和QueryBuilder,我尝试了很多东西,但不明白如何写它。
这里有一些链接到我的2教义实体:
Entity Product
Entity Project
感谢您的帮助!

n9vozmp4

n9vozmp41#

校样:

$sql2 = "select p from ArtoAcvBundle:Project p join ArtoAcvBundle:Product prod where prod.weight <> 0 and p.green_user_id =:userId";
798qvoo8

798qvoo82#

是的,非常感谢找到了这个解决方案。我继续搜索,发现Doctrine中存在一个bindValue()方法。
因此,我传递了修改过的原始SQL的参数,它工作正常

disho6za

disho6za3#

使用QueryBuilder的示例

// select p from ArtoAcvBundle:Project p join prod ArtoAcvBundle:Product on prod.project_id = p.id where prod.weight <> 0 and p.green_user_id =:userId

$query = $this->getRepository(Project::class)->createQueryBuilder('p');
$query->join('p.products' , 'prod')
      ->andWhere('prod.weight <> 0')
      ->andWhere('p.greenUser = :user')
      ->addParameter('user', $youruserEntity);

return $query->getQuery()->getResult();

相关问题