douyan4470 2018-06-04 04:55
浏览 264
已采纳

Yii2:在find() - > where()方法中的orderby

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 !!

  • 写回答

2条回答 默认 最新

  • douhan5853 2018-06-04 07:00
    关注

    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']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵