2015-01-03 4 views
1

저는 피봇 테이블 (ingredients_recipe)과 함께 Ingredient와 Recipe 사이에 많은 관계가 있습니다.Laravel : many-many 관계를 주문하시오.

조리법을 몇 개나 주문했는지 주문하고 싶습니다. 예를 들어, 내가 2 가지 조리법에서 소금을 사용하고 3 가지 조리법에서 고기를 사용한다면 소금 전에 고기를 먹을 것입니다.

이것은 내가 가지고있는 것입니다. 그것은 작동하지만 올바르게 질서를 내 DB에서 직접 실행되는 결과가 예상대로 작동하기 때문에 Laravel이 내부적으로 뭔가를하고 있다고해도 맞지 않습니다.

//Ingredient model 
public function recipesCount() 
{ 
    return $this->belongsToMany('Recipe')->selectRaw('count(ingredient_recipe.recipe_id) as aggregate')->orderBy('aggregate', 'desc')->groupBy('ingredient_recipe.ingredient_id'); 
} 

public function getRecipesCountAttribute() 
{ 
    if (! array_key_exists('recipesCount', $this->relations)) $this->load('recipesCount'); 

    $related = $this->getRelation('recipesCount')->first(); 

    return ($related) ? $related->aggregate : 0; 
} 

//controller 
$ingredients = Ingredient::with('recipesCount')->whereHas('recipes', function($q) 
        { 
          $q->where('user_id', Auth::id()); 

        })->take(5)->get(); 

//outputting the last query here and executing it on my db returns correctly ordered results. 

어떻게 해결할 수 있습니까?

답변

0

order by 관련 테이블에 join이 필요합니다. 무엇이든 열심히 로딩하여 그것을 달성 할 수있는 방법이 없습니다. inner joins 당신을 위해 일을 할 것입니다 위해

Ingredient::with('recipesCount') 
    ->join('ingredient_recipe as ir', 'ir.ingredient_id', '=', 'ingredients.id') 
    ->join('recipes as r', function ($j) { 
     $j->on('r.id', '=', 'ir.recipe_id') 
      ->where('r.user_id', '=', Auth::id()); 
    }) 
    ->orderByRaw('count(r.id) desc') 
    ->groupBy('ingredients.id') 
    ->take(5) 
    ->get(['ingredients.*']); 

whereHas에 대한 필요는 더 이상 없습니다.

+0

감사합니다. 나는 "with ('recipesCount')"를 더 이상 필요로하지 않는다고 생각했지만 여전히 같은 쿼리에서 SELECT에 추가 할 수 있다고 생각하지만 그래도 조사해야합니다. – koichirose

+0

'with ('recipesCount ')'와 recipeNumber'로'select count (r.id)'를 삭제하는 것이 좋습니다.'recipesCount'와 같은 이름을 사용하지 마십시오. 어쨌든 관계 쿼리를 호출하게 될 것이기 때문입니다. –

관련 문제