Yii2 多对多关系的订单项 [英] Yii2 order items of many-to-many relation

查看:18
本文介绍了Yii2 多对多关系的订单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个与连接 (slider_images) 表相关的表(滑块、图像),关系工作正常但我需要以特定顺序获取相关数据,定义正确顺序的属性在连接表中,关系定义为:

I've 2 tables (sliders, images) related with junction (sliders_images) table, the relation work fine but I nedd to get related data with specific order, the attribute that define the right order is in the junction table, the relation is defined as:

public function getImages(){
    return $this->hasMany(Images::className(), ['id' => 'image_id'])
        ->viaTable('sliders_images', ['slider_id' => 'id'], function($query){
            $query->orderBy('sliders_images.display_order ASC');
        });
}

当我调用 $model->images 时,我收到了正确的图像但顺序错误,使用 foreach 图像是按 id 排序的,我如何才能获得按其他属性排序的图像?

when i call $model->images I receive the correct images but the wrong order, using foreach the images was ordered by id, how i can get the images ordered by other attribute?

推荐答案

正确的做法是添加join withjunction table ->joinWith('slidersImages') 获取joint table的属性然后按其中之一订购.完整代码:

The right way is to add a join with junction table ->joinWith('slidersImages') for get the junction table attributes and then order by one of those. The full code:

public function getImages(){
        return $this->hasMany(Images::className(), ['id' => 'image_id'])
        ->via('slidersImages')
        ->joinWith('slidersImages SI')
        ->orderBy('SI.display_order ASC');
}

这篇关于Yii2 多对多关系的订单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆