doctrine-orm - 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")
我已经尝试了很多来完成这项工作,但它不会......有什么想法吗?
解决方案
我认为您应该为每个场景使用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 语句结果
希望这有帮助
推荐阅读
- r - rhandsontable 格式化日期时显示错误的日期格式
- javascript - 为什么 Javascript 的语言设计不包括在使用变量之前等待变量解析?
- android - 这个 Runnable 类会导致内存泄漏吗?
- c# - c# WPF 需要帮助:如何通过 WPF 显示对象中的值
- r - R - 在第一组引号内返回字符串
- docker - 有没有 docker 镜像保留政策?
- tensorflow - 如何使用 Tensorboard 确定重要特征?
- html - 为什么我的锚中不显示 Font Awesome 图标?
- rest - 具有相同 REST 资源的多种身份验证方法
- django-rest-framework - 创建具有两级父表的django rest框架ViewSet