Yii2 order items of many-to-many relation(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 多对多关系的订单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Yii2 多对多关系的订单项


基础教程推荐
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的foreach复选框POST 2021-01-01
- php中的PDF导出 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01