2017-10-18 5 views
0

나는 다음과 같은 모델이 있습니다Laravel 5.2 : 피벗 테이블 필드에 의해 주문 모델

- User: 
id 

- Product: 
id 
lid 
user_id 

- ProductCategories: 
product_id 
category_id 
lid 

- Category: 
id 

관계 :

사용자 hasMany의 제품

제품 belongsToMany 카테고리

내가 사용자를 가지고 카테고리 ID가 있습니다. 해당 카테고리의 제품이 필요합니다. ProductCategory

가장 적합한 솔루션은 무엇입니까?

현재이 내가 사용하는 트링하고있는 무슨이지만, 그것은 올바른 방법으로 주문하지 않습니다

$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);