如何在数组字段中查询包含所有给定值的模型?[理论ORM和ODM QueryBuilder]
给定模型如何在数组字段中查询包含所有给定值的模型?[理论ORM和ODM QueryBuilder],orm,doctrine-orm,query-builder,odm,Orm,Doctrine Orm,Query Builder,Odm,给定模型Post,该模型有一个字段标记,该字段包含一个字符串数组,例如: Post: id: 1 tags: ['a', 'b', 'c'] Post: id: 2 tags: ['a', 'z'] 如何构造一个查询,以从数组['a',b']获取包含所有值的模型(在本例中,仅返回Post id 1) 我一直在想: 使用ODM QueryBuilder: // is this correct? $qb->expr()->field('tags')->all(
Post
,该模型有一个字段标记
,该字段包含一个字符串数组,例如:
Post:
id: 1
tags: ['a', 'b', 'c']
Post:
id: 2
tags: ['a', 'z']
如何构造一个查询,以从数组['a',b']
获取包含所有值的模型(在本例中,仅返回Post id 1)
我一直在想:
使用ODM QueryBuilder:
// is this correct?
$qb->expr()->field('tags')->all( array('a', 'b') );
$qb->expr()->all( /* the docs say to use DQL here.. is there no QueryBuilder alternative? */ )
使用ORM QueryBuilder:
// is this correct?
$qb->expr()->field('tags')->all( array('a', 'b') );
$qb->expr()->all( /* the docs say to use DQL here.. is there no QueryBuilder alternative? */ )
我被
数组
类型映射名称误导了。如果仔细阅读文档,您将了解到不存在array
这样的数据库类型
那么array
映射到什么类型呢?anwser是文本
。这意味着您可以对其执行类似于的操作(尽管这些操作可能会对性能造成一些影响)
因此,为了回答我自己的问题,为了实现这样的目标,我必须构建如下内容:
$qb->where($qb->expr()->andX(
$qb->expr()->like('tags', '?1'),
$qb->expr()->like('tags', '?2'),
$qb->expr()->like('tags', '?3')
))->setParameters(array(
1 => '%"a"%',
2 => '%"b"%',
3 => '%"c"%'
));