Home > Blockchain >  How to ignore where clause if condition is empty in Yii2
How to ignore where clause if condition is empty in Yii2

Time:11-29

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.

CodePudding user response:

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.

CodePudding user response:

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);
  • Related