问题描述
我有 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 多对多关系的订单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)