我有以下型号:
- User:
id
- Product:
id
lid
user_id
- ProductCategories:
product_id
category_id
lid
- Category:
id
关系:
用户拥有多种产品
产品属于多个类别
我有一个用户,我有一个类别ID,我需要从ProductCategory
的盖子订购属于该类别的产品最佳解决方案是什么?
目前这是我要使用的内容,但它没有以正确的方式排序:
$products = $user->products()->whereHas('categories', function($q) use ($category){
$q->where('category_id', $category)->orderBy('product_categories.lid', 'asc');
})->paginate(20);
答案 0 :(得分:0)
溶剂是:
$products = $user->products()->whereHas('categories', function($q) use ($category){
$q->orderBy('product_categories.lid', 'asc');
})
->leftJoin('product_categories', 'products.id', '=', 'product_categories.product_id')
->leftJoin('categories', 'product_categories.category_id', '=', 'categories.id')
->where('product_categories.category_id', $category)
->select('products.*')
->orderBy('product_categories.lid', 'asc')->paginate(20);