0

Given model Post which has a field tags which holds an array of strings, eg:

Post:
  id: 1
  tags: ['a', 'b', 'c']

Post:
  id: 2
  tags: ['a', 'z']

How to construct a query, to get models containing all values from array ['a', 'b'] (in this example, return only Post id 1)?

I've been thinking about these:

Useing Doctrine ODM QueryBuilder:

// is this correct?
$qb->expr()->field('tags')->all( array('a', 'b') );

Useing Doctrine ORM QueryBuilder:

$qb->expr()->all( /* the docs say to use DQL here.. is there no QueryBuilder alternative? */ )
ioleo
  • 4,697
  • 6
  • 48
  • 60

1 Answers1

1

I was misled by the array type mapping name. If you read carefully the docs, you will learn that there is no such database type as array.

So what type is array mapped to? The anwser is text. Which means you can do LIKE operations on it (although, these may cause some performance impact).

So, to anwser my own question, to achieve such goal I'd have to construct something like:

$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"%'
));
ioleo
  • 4,697
  • 6
  • 48
  • 60