Php 5个表之间的拉维关系
请询问从MN表中获取数据的正确方法是什么,其中一个产品分配了多个标记/型号/年份组合 例如,ID为1的产品在mmis表中有以下内容:Php 5个表之间的拉维关系,php,laravel,orm,Php,Laravel,Orm,请询问从MN表中获取数据的正确方法是什么,其中一个产品分配了多个标记/型号/年份组合 例如,ID为1的产品在mmis表中有以下内容: id | product_id | mark_id | model_id | year_id 178 1 1 1 2 177 1 2 1 3 176 1 3 1
id | product_id | mark_id | model_id | year_id
178 1 1 1 2
177 1 2 1 3
176 1 3 1 1
其他表格包括:标记、型号、年份。
只需执行以下操作即可获取所有请求的数据:
$items = ProductMmi::where('product_id', $id)
->with(['mark', 'model', 'year'])
->get();
问题是,以这种方式,我无法根据mark.name ASC、model.name ASC、year.name ASC对结果进行排序
谢谢你的建议
更新:
忘记添加我的第二次尝试-订购仍有问题
$items = ProductMmi::select([
'product_mmis.*',
'marks.*',
'mark_models.*',
'mark_model_years.*'
])
->join('marks', 'product_mmis.mark_id', '=', 'marks.id')
->join('mark_models', 'product_mmis.model_id', '=', 'mark_models.id')
->join('mark_model_years', 'product_mmis.year_id', '=', 'mark_model_years.id')
->where('product_mmis.product_id', $id)
->orderBy('mark', 'asc')
->orderBy('model', 'asc')
->orderBy('year', 'asc')
->get();
你可以用这种方式
$items = ProductMmi::where('product_id', $id)->with(['mark'=>function($query){
$query->orderBy('your_column_name','ASC');
}])->with(['model', 'year'])
->get();
或者,如果您不想编辑查询,那么在模型中也可以这样做
public function mark()
{
return $this->hasMany(Mark::class)->orderBy('mark','asc');
}
我认为解决方案是在特定联接之间添加orderBy方法。例如,以下情况完全正常工作:
$items = ProductMmi::select([
'product_mmis.*',
'marks.*',
'mark_models.*',
'mark_model_years.*'
])
->join('marks', 'product_mmis.mark_id', '=', 'marks.id')
->orderBy('mark', 'asc')
->join('mark_models', 'product_mmis.model_id', '=', 'mark_models.id')
->orderBy('model', 'asc')
->join('mark_model_years', 'product_mmis.year_id', '=', 'mark_model_years.id')
->where('product_mmis.product_id', $id)
->orderBy('year', 'desc')
->get();
是否有更好的方法以更有效的方式完成?谢谢