问题描述
在建立数据库表与表之间的关系的时候,product
表关联 product_img
表, product_img
表又关联到img
表。
但是在商品详情展示中吗,必须要求product_img
的图片按顺序排列,所以,在数据库里设计了一个字段 ‘order’
排序用。
以往解决方案
按照往常的惯例,我们在模型中直接对字段进行排序即可
public static function getMostRecent($count){
$product = self::limit($count)
->order('create_time','desc')
->select();
return $product;
}
但是这里是在Product
模型中对ProductImage
和ProductPropertry
进行关联,而商品属性的图片是在ProductImage
模型之下的,所以必须另寻他法。
新的解决方案
public static function getProductDetail($id)
{
//对order字段进行排序
$product = self::with([
'imgs' => function($query){
$query->with('imgUrl')
->order('order','ace');
}
])
->with(['properties'])
->find($id);
return $product;
}
这里在链式查询时写了一个闭包函数,层层深入,可见闭包函数的灵活性之高。