简体   繁体   中英

How to find ActiveRecords which have attribute either equal to value or be null in Yii2

I basically have an active query and I either want to filter that column if it matched the ID or is null

MyTable::find()->andFilterWhere(['in', 'org_id', [null, $org_id]])->all();

currently using this, works fine for the $org_id , but it will not return null values. I tried this to see if I could get any null results, but no avail

MyTable::find()->andFilterWhere(['in', 'org_id', null])->all();

Any tips?

Correct you query like that:

MyTable::find()
   ->andFilterWhere(['in', 'org_id', $this->org_id])
   ->orWhere(['org_id' => null])
   ->all();

You can specify IS NULL condition with array also, orWhere is enough because this condition does not depend on attribute value.

如果您使用的是多个值的过滤器,则以下查询将导致数组中包含null或值的单元格:

$query->andWhere(['or', ['in', 'column', $value_array], ['column' => null]]);

To reinforce arogachev's answer, this is a good reference, if you wanted to just query for null results: https://github.com/yiisoft/yii2/issues/6788

$query->andfilterWhere('org_id' => null)

This query doesn't work because filterWhere removes empty params.

For null results, use:

$query->andWhere('org_id' => null)

To completely answer this question, let's reiterate what we really want.

We need to get all records from some table which have some specific 'field' to be equal either to given $value or to null .

Given that definition, we can translate it directly into Query call:

$query->andWhere(['or', ['field' => $value], ['field' => null]]);

This is somewhat suboptimal in cases when $value is null , because it gives the SQL WHERE (field IS NULL) OR (field IS NULL) . You can mitigate it by wrapping the andWhere call with if statement:

if ($value === null)
    $query->andWhere(['field' => null]);
else
    $query->andWhere(['or', ['field' => $value], ['field' => null]]);

or depending on your tastes, using ternary operator:

$query->andWhere(
    $value === null
        ? ['field' => null]
        : ['or', ['field' => $value], ['field' => null]]
);

In any case, using andFilterWhere completely defeats the purpose of your query, because it exists solely to remove pieces like ['field' => null] from the queries.

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