Yii2 多对多关系的订单项

2022-01-07 00:00:00 php yii2 yii2-advanced-app activerecord

我有 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');
}

相关文章