简体   繁体   中英

How to pass array into the where condition?

I have dynamic where conditions. They consist of the following array:

array:2 [
  "brand_name" => array:2 [
    0 => "a"
    1 => "b"
  ]
  "category_type" => array:1 [
    0 => "AA"
  ]
]

I need to apply where conditions to my query.

$em = $this->getEntityManager();
$sql = " select * from products as p";

$i = 0;
foreach ($wheres as $key => $value) {
    if ($i === 0) {
        $sql .= " WHERE";
    } else {
        $sql .= " AND";
    }
    $sql.= " te.$key IN (:$key)";
    $i +=1;
}

I am not sure how to assign the value to the query. If I had single where condition, I did something like this:

$params = array(
            $ids,
        );
        $query = $em->getConnection()->executeQuery(
            $sql,
            $params,
            array(
                \Doctrine\DBAL\Connection::PARAM_STR_ARRAY,
                \PDO::PARAM_INT,
            )
        );
        $records = $query->fetchAll();

But I don't know how to fix where where conditions are in dynamic.

This is very easy using the query builder. It's the kind of thing it was designed for.

Something like this would take you there:

$qb = $this->createQueryBuilder('p');

$suffix = 0;
foreach ($conditions as $key => $value) {
    $parameter = 'query_' . $suffix++;

    $qb->andWhere("p.$key IN :$parameter")
        ->setParamter($parameter, $value);
}

$records = $qb->getQuery()->getResult()

You'll need to make adjustments to suit your data model. In your question you are selecting products as p , but then you are trying to select from te , so I guess some pieces are missing from the puzzle.

But you should be able to finish it from here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM