简体   繁体   English

如何将数组传递给 where 条件?

[英]How to pass array into the where condition?

I have dynamic where conditions.我有动态 where 条件。 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.我需要将 where 条件应用于我的查询。

$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:如果我有单一的 where 条件,我会这样做:

$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.您需要进行调整以适应您的数据 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.在您的问题中,您选择products as p ,但随后您尝试 select 来自te ,所以我想拼图中缺少一些部分。

But you should be able to finish it from here.但是你应该可以从这里完成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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