vương Thong
vương Thong

Reputation: 47

Yii2: orderby in find()->where() method

I'm trying to make a query to the database to retrieve a list of favorite products by category

In the category there is an attribute called sortcode after that I have a $categoryids : [3242,1231,6343,1232] and products

$products = Product::find()->where(['category'=>$categoryids])->all();

But the result was not as I expected, item in $products sort by index Now I want all product in category 3242 should be ranked first, then to 1231 ... How do I get the results I want? Sorry for my bad English! Thanks in advance and have a nice day !!

Upvotes: 0

Views: 2604

Answers (2)

Alank_Ilalank
Alank_Ilalank

Reputation: 186

try to use where in condition

$products = Product::find()
     ->where(['in','category',$categoryids])
     ->orderBy('category DESC')
     ->all();

or if you want to sort it by category's shortcode you should join with categorys table, not tested yet but should works :

$products = Product::find()
    ->where(['in','category',$categoryids])
    ->joinWith(['categorys' => function ($query) {
        $query->orderBy('shortcode');
    }])
    ->all();

don't dorget to add categorys relations in your Product's model.

public function getCategorys()
{
    return $this->hasOne(Category::className(), ['id' => 'category']);
}

Upvotes: 3

vishuB
vishuB

Reputation: 4261

Refer Yii2 orderBy()

$products = Product::find()
            ->where(['category'=>$categoryids])
            ->orderBy(['here_your_category_id' => SORT_ASC])
            ->all();

Upvotes: 1

Related Questions