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

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

问题描述

我有2个与联结表(sliders_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?

推荐答案

正确的方法是添加带有联接表-> joinWith('slidersImages')的联接以获取联接表属性然后按其中之一排序。完整代码:

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天全站免登陆