Php Laravel-连接四个表

Php Laravel-连接四个表,php,mysql,sql,laravel,laravel-4,Php,Mysql,Sql,Laravel,Laravel 4,我有下列表格 Recipe: - id - name - image Ingredients: - id - title - image (pivot) recipes_ingredients - id - recipe_id - ingredients_id votes: - id - rating - recipe_id 我怎样才能连接四张桌子 我需要什么: 对于每种配料(flag==1),我需要6个随机配方,其中也有投

我有下列表格

Recipe:  
- id  
- name  
- image  

Ingredients:  
- id  
- title  
- image  

(pivot) recipes_ingredients  
- id  
- recipe_id  
- ingredients_id  

votes:  
- id  
- rating  
- recipe_id  
我怎样才能连接四张桌子

我需要什么:
对于每种配料(flag==1),我需要6个随机配方,其中也有投票权



在FOREACH中使用
$component->recipes
,然后使用
$recipe->评级(这应该可以做到:

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

如果你想要的是像第一行一样快速加载,为什么要尝试加入所有这些表?因为我不知道如何从每个配方的评级中获得avg()!你的闭包有一些古怪的语法:
“recipes”=>function($q)=>function()
这很奇怪,你在哪里加入投票表?这意味着什么“按配方从投票组中获取id”。是否正确?!我想用解决方案编辑了我的问题..经过一些修改后似乎可以正常工作!谢谢!投票被加入到检索配方的第二个查询中(检查使用急切加载运行的查询),并按配方id分组,否则它将只返回一行,因为聚合函数就是这样工作的。
        $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);  
        $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();  
        $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();
$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();