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.
어떻게 해결할 수 있습니까?
감사합니다. 나는 "with ('recipesCount')"를 더 이상 필요로하지 않는다고 생각했지만 여전히 같은 쿼리에서 SELECT에 추가 할 수 있다고 생각하지만 그래도 조사해야합니다. – koichirose
'with ('recipesCount ')'와 recipeNumber'로'select count (r.id)'를 삭제하는 것이 좋습니다.'recipesCount'와 같은 이름을 사용하지 마십시오. 어쨌든 관계 쿼리를 호출하게 될 것이기 때문입니다. –