首页 > 解决方案 > QueryBuilder:在包含逗号分隔整数的列中搜索值

问题描述

我有一列tags包含逗号分隔列表中的 id。我想搜索给定值在该列中的所有行。

假设我有两行,其中的列tags如下所示:

Row1: 1,2,3,4
Row2: 2,5,3,12

我想搜索该列包含的行1。我尝试这样做:

$qb = $this->createQueryBuilder('p')
      ->where(':value IN (p.tags))
      ->setParameter('value', 1);

我希望它做类似的事情

SELECT p.* FROM mytable AS p WHERE 1 IN (p.tags)

在 MySQL 中直接执行此操作完美。在教义中它不起作用:

Error: Expected Literal, got 'p'

但是,它可以反过来工作,但这不是我需要的:

->where("p.tags IN :value")

我已经尝试了很多来完成这项工作,但它不会......有什么想法吗?

标签: doctrine-orm

解决方案


我认为您应该为每个场景使用LIKE函数,例如:

        $q = "1";

        $qb = $this->createQueryBuilder('p')
        ->andWhere(
            $this->expr()->orX(
                $this->expr()->like('p.tags', $this->expr()->literal($q.',%')),  // Start with...
                $this->expr()->like('p.tags', $this->expr()->literal('%,'.$q.',%')), // In the middle...
                $this->expr()->like('p.tags', $this->expr()->literal('%,'.$q)),  // End with...
                ),
        );

查看此小提琴中的 SQL 语句结果

希望这有帮助


推荐阅读