我有以下表格
Recipe:
- id
- name
- image
Ingredients:
- id
- title
- image
(pivot) recipes_ingredients
- id
- recipe_id
- ingredients_id
votes:
- id
- rating
- recipe_id
如何加入四张桌子?
我需要什么:
对于每种成分(有标志== 1),我需要6个随机食谱,其中也有投票。
像
前一个$ingredient->recipes
,然后是$recipe->rating (<-- AVG(ranking))
这是我的第一次尝试,但没有奏效:
$ingredients = Ingredients::with('recipes')
->where('ingredients.is_product',1)
->where('recipes.status', '=', '1')
->join('ingredient_recipe', 'ingredient_recipe.ingredients_id', '=', 'ingredients.id')
->join('recipes', 'ingredient_recipe.recipe_id', '=', 'recipes.id')
->select(array('ingredients.*'))
->get();
基于此查询:
$bestThreeRecipes = Recipe::with('user')
->where('recipes.status', '=', '1')
->join('votes', 'votes.recipe_id', '=', 'recipes.id')
->select(array('votes.*','recipes.*',DB::raw('AVG(rating) as ratings_average, COUNT(rating)')))
->groupBy('recipes.id')
->orderBy('ratings_average', 'DESC')
->get()->take(4);
(这很好用!)
你知道吗?谢谢! 编辑#1:
现在我尝试了这个:
$ingerdients = Ingredients::with(array('recipes','recipes.votes'))
->where('ingredients.is_product',1)
->where('recipes.status', '=', '1')
->join('ingredient_recipe', 'ingredient_recipe.ingredients_id', '=', 'ingredients.id')
->join('recipes', 'ingredient_recipe.recipe_id', '=', 'recipes.id')
->select(array('ingredients.*'))
->get();
但我仍然不知道如何让AVG()只为食谱工作!
编辑#2 - 解决方案(暂时):
这似乎有效,多亏了十几岁!
$ingredients = Ingredients::with(array(
'recipes' => function ($q) {
$q->where('recipes.status', '=', '1')
->join('votes','recipes.id','=','votes.recipe_id')
->select(DB::raw('avg(rating) AS rating'))->groupBy('recipes.id')->orderBy('rating', 'DESC');
}))
->where('ingredients.is_product',1)
->get();
答案 0 :(得分:1)
这应该可以解决问题:
$ingredients = Ingredients::with(array(
'recipes' => function ($q) {
$q->where('recipes.status', '=', '1')
->join(
DB::raw('(SELECT AVG(rating) as rating, COUNT(rating) as ratingCount, id from votes group by recipe_id) as votes'),
'recipes.id',
'=',
'votes.recipe_id')
->select('votes.rating', 'votes.ratingCount');
}))
->where('ingredients.is_product',1)
->get();