fala
fala

Reputation: 271

How can I filter my doctrine request by the values of an array?

I am loading data from my database with doctrine:

$data = $this->em->getRepository('App\\Entity\\Data')->allData();

That creates an array with a lot of data:

PagesGenerator.php on line 259:
array:1696 [▼
  0 => Data^ {#5430 ▼
    -id: 2298
    -uuid: "426441e418"
    -content: "two"
    -document_id: "93b7dc32f4"
  }
  1 => Data^ {#5434 ▼
    -id: 2299
    -uuid: "c1474a87a9"
    -content: ""
    -document_id: "93b7dc32f4"
  }
  2 => Data^ {#5413 ▼
    -id: 2300
    -uuid: "8bfd9b4893"
    -content: "three"
    -document_id: "edb8fa9647"
  }
  3 => Data^ {#5427 ▶}
  4 => Data^ {#5428 ▶}
  5 => Data^ {#5433 ▶}
  6 => Data^ {#5431 ▶}
  7 => Data^ {#5429 ▶}

I have another array $docIds:

array:96 [▼
  0 => "3019b7a82f"
  1 => "b1a4c67080"
  2 => "82cf4392d7"
  3 => "55768e0955"
  4 => "74c6217001"
  5 => "71fc4c3ebf"
  6 => "35e2d3a1c6"
  7 => "50c940b223"
  8 => "2561ff454d"
  9 => "bb447530e1"

To get a fast performance I like to prefilter the array $data to contain only entries with document_ids that are values in my array $docIds;

This is my approach:

$data = $this->em->getRepository('App\\Entity\\Data')->filterByDocID($docIds);

In my Data Repository:

public function filterByDocID($array)
{
  $query = $this->getEntityManager()
  ->createQuery(
    "SELECT a
    FROM App\Entity\Data a
    WHERE document_id IN ('".$array."')");
    try {
      return $query->getResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
      return null;
    }
  }

But I get the error message:

Notice: Array to string conversion

Upvotes: 0

Views: 440

Answers (1)

spyro95
spyro95

Reputation: 146

There are two possiblities.

As they already wrote, you can implode your array.

WHERE document_id IN ('".implode(',', $array)."')");

or you're binding the array.

$stmt->bindValue(0, array(123, 234, 345, 456, 567, 678));

I would prefer binding the array, since this would be much cleaner than imploding and parsing as string.

E:

Since youre using strings as id, try the following:

WHERE document_id IN ('".implode("', '", $array)."')");

Otherwise try using LIKE

Upvotes: 1

Related Questions