简体   繁体   中英

How to ignore where clause if condition is empty in Yii2

I know this same question is already asked before. But I have tried the solution but it's not working for me.

 $comp_ids = AllowArea::find()
    ->select(['comp_code'])
    ->where(['user_id' => Yii::$app->user->id])
    ->column();

    $ref = (new \yii\db\Query())
        ->select([
            'ProductCode',
            'ProductNameFull',
            'ProductSpec',
            'ProductGroup',
            'CompanyCode',
            'CompanyName'
            ,'Price',
            'PurchasePrice'
        ])->from('Product')
        ->andFilterWhere(['CompanyCode' =>  $comp_ids])
        ->all(Yii::$app->sds);

It's giving me empty data.

Flow The users are assigned areas and some users are assigned areas with a company. So I want the above query to return me the result whether the condition fails or not.

Update 1 The SQL which I am getting is

SELECT `ProductCode`, `ProductNameFull`, `ProductSpec`, `ProductGroup`, 
`CompanyCode`, `CompanyName`,
`Price`, `PurchasePrice` FROM `Product` WHERE `CompanyCode` IS NULL

Any help would be highly appreciated.

If nothing works, from what you were told, then you can try:

$ref = (new \yii\db\Query())
    ->select([
        'ProductCode',
        'ProductNameFull',
        'ProductSpec',
        'ProductGroup',
        'CompanyCode',
        'CompanyName'
        ,'Price',
        'PurchasePrice'
    ])->from('Product');

if (!empty($comp_ids)) {
    $ref->andFilterWhere(['CompanyCode' => $comp_ids]);
}

$ref = $ref->all(Yii::$app->sds);

Try user orFilterWhere() this Adds an additional WHERE condition to the existing one but ignores empty operands. The new condition and the existing one will be joined using the 'OR' operator. This method is similar to orWhere(). The main difference is that this method will remove empty query operands. As a result, this method is best suited for building query conditions based on filter values entered by users.

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