2014-04-18 91 views
0

我有一个非常奇怪的问题,与我多对多的关系。Laravel - 关系数据缺失

此功能:

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

应该让我所有的配料和食谱吧。问题是,一些配料食谱缺失。

该加入不起作用。
我在recipe_id = 1和= 2中添加了recipe_id = 7,它只在ingredient_id = 1中显示此配方,但不在2中。
如果我更改主元ID(假设成分= 1是1并且2是在2),我改变成分_ID 1 2和副verca,与7的食谱是在ingredient_id = 2,但不是在1了。

但它应该在两个成分。为什么? 这就像连接认为“好吧,我已经添加到ID之前,所以跳过这个ID”。

我的模型:

Recipe.php

public function ingredients() { 
     return $this->hasMany('Ingredients','ingredients_recipe','recipe_id','ingredients_id')->withPivot('amount'); 
} 

Ingredients.php

public function recipes() { 
     return $this->belongsToMany('Recipe','ingredients_recipe','ingredients_id','recipe_id')->withPivot('amount'); 
} 

编辑#1:
好吧,我想通了,如果我删除函数()为投票,它工作正常。那里发生了什么?我需要为每个配方评分。

回答

0

明白了:

 $ingredients = Ingredients::with(array('recipes','recipes.votes' => function ($q) { 
     $q->where('recipes.status', '=', '1') 
      ->join('recipes','votes.recipe_id','=','recipes.id') 
      ->select(DB::raw('avg(rating) AS rating'))->groupBy('recipes.id')->orderBy('rating', 'DESC'); 
     })) 
     ->where('ingredients.is_product',1) 
     ->get(); 

显然我不得不recipes.votes添加到阵列中,并在该连接而不是在带票食谱。现在我加入食谱和(recipes.votes)。这工作!奇怪!