Search code examples
yii2yii2-model

Yii2: How do I write the below Active Query?


Using this solution, how can I get my $conditions variable to my active query?

$conditions = 'main_category_id != :main_category_id', ['category_status' => 1, 'main_category_id' => 0, 'sub_category_id' => $id,'type'=> 4];

$result = Category::find()->where($conditions)->orderby('category_name ASC')->all();

On my query main_category_id != 0. Any other solution that works is also fine

Please note that I need $conditions variable as they vary. Here is my query with if statements:

    public function get_subcategory_list($id="",$type="")
{
    $conditions = ['category_status' => 1, 'main_category_id' => 0, 'main_category_id' => $id, 'type' => 2];
    if($type == 2){
        $conditions = ['category_status' => 1, 'main_category_id' => 0, 'sub_category_id' => $id, 'type' => 3];
    }
    if($type == 3){
        $conditions = ['category_status' => 1, 'main_category_id' => 0, 'sub_category_id' => $id,'type'=> 4];
    }
    $result = Category::find()->where($conditions)->orderby('category_name ASC')->all();
    return $result;
}

Please note that $conditions works fine on the above function the only problem is here main_category_id should not be equal to 0.


Solution

  • You can't assign variable ($conditions) like you did, it's not valid.

    Your ActiveQuery can be written like this:

    $models = Category::find()
        ->where(['<>', 'main_category_id', 0])
        ->andWhere([
            'category_status' => 1,
            'sub_category_id' => $subCategoryId,
            'type'=> 4,
        ])
        ->orderBy(['category_name' => SORT_DESC])
        ->all();
    

    You can replace <> with != or not in in case of using array of main category ids.

    Read more about constructing where conditions in official docs.

    Update: No need to change the whole $conditions array and copy-paste. You can calculate the $type for example like this:

    switch ($type) {
        case 2:
            $typeValue = 3;
    
            break;
        case 3:
            $typeValue = 4;
    
            break;
        default:
            $typeValue = 2;
    }
    

    This logic is a little bit weird (maybe increment +1 will be better).

    Then just insert $typeValue instead of static value here 'type'=> $typeValue.

    Even you have some complex query constructing, you can divide query in separate where / orWhere / andWhere and dynamically change it.