2017-10-18 126 views
0

我有以下型號:Laravel 5.2:排序數據透視表中的字段模式

- User: 
id 

- Product: 
id 
lid 
user_id 

- ProductCategories: 
product_id 
category_id 
lid 

- Category: 
id 

關係:

用戶的hasMany產品

產品belongsToMany類別

我有一個用戶和我有一個類別ID,我需要屬於該類別的產品,按產品類別

這是最好的解決方案是什麼?

目前,這就是我特林使用,但它不正確的方式排序:

$products = $user->products()->whereHas('categories', function($q) use ($category){ 
    $q->where('category_id', $category)->orderBy('product_categories.lid', 'asc'); 
})->paginate(20); 

回答

0

的sollution是:

$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); 
相關問題