首页 > 解决方案 > 具有多个值的参数的学说查询

问题描述

我想做一个学说查询,其中每个参数可以有多个值(来自一个选择多个)。

我有一个表,其“类型”参数的值可以为 1、2、3 或 4,而“在线”参数的值可以为 0 或 1。

到目前为止,我的查询如下:

$query = $this->createQueryBuilder('properties');

if (array_key_exists('type', $searchValues)) {

    $types = $searchValues['type'];
    $iterator = 0;

    foreach ($types as $type) {

        if ($iterator == 0) {

            $query->andWhere('properties.idPropertyType = ' . $type);

        } else {

            $query->orWhere('properties.onlineProperties = ' . $type);

        }

            $iterator++;

        }
    }

if (array_key_exists('status', $searchValues)) {

    $status = $searchValues['status'];
    $iterator = 0;

    foreach ($status as $statu) {

        if ($iterator == 0) {

            $query->andwhere('properties.onlineProperties = ' . $statu);

        } else {

            $query->andWhere('properties.onlineProperties = ' . $statu);

        }

        $iterator++;

    }

}

$properties = $query->getQuery()->getResult();

在参数类型 = 1 且在线 = 0 和 1 的搜索的情况下,我得到的结果类型是另一个值而不是 1。我理解原因,但我无法找出进行查询的正确方法。

标签: doctrine-query

解决方案


您不需要手动构建查询,只需使用 QueryBuilder 类中的 (in) 函数即可。试试这个:

$query = $this->createQueryBuilder('properties');

if(array_key_exists('type', $searchValues)){
    $types = $searchValues['type'];
    $query->andWhere($query->expr()->in('properties.idPropertyType', $types));
}

if(array_key_exists('status', $searchValues)){
    $status = $searchValues['status'];
    $query->andwhere($query->expr()->in('properties.onlineProperties', $status));
}

$properties = $query->getQuery()->getResult();

推荐阅读