2014-04-14 37 views
0

用户可以将成分保存到购物清单。现在,当用户登录并访问食谱时,购物清单小工具正在向他显示,他的清单中已包含哪些成分,这就是我的问题。Laravel - 检查是否有多对多的关系

在这里我得到的所有成分的配方:

$recipe = Recipe::find($id); 
$recipe->load('ingredients'); 

在$配方相关>成分

做工精细用一个foreach在这里,我gettingthe购物列表中的用户对这个食谱,如果他有一个:

if(Auth::check()) { 
    $list = ShoppingList::with('ingredients')->where('recipe_id',$id)->where('user_id',Auth::user()->id)->get(); 
//... 
} 

在这里,我想检查一下,如果保存的成分是购物清单上:

  foreach($recipe->ingredients as $i) { 
      foreach($list as $l) { 
       $ingredient = Ingredients::where('id','=',$l->ingredients_id)->get(); 
       $i->isAdded = (count($ingredient) > 0) ? 1 : 0; 
      } 

     } 

但不知何故,这是完全错误的。我错过了什么?

关系:
方药:

public function user() { 
     return $this->belongsTo('User','user_id'); 
} 
public function lists() { 
     return $this->hasMany('ShoppingList','recipe_id'); 
} 

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

购物清单:

public function user() { 
     return $this->belongsTo('User','id'); 
} 
public function recipe() { 
     return $this->belongsTo('Recipe','recipe_id'); 
} 
public function ingredients() { 
     return $this->belongsToMany('Ingredients','shopping_list_ingredients','shopping_list_id','ingredients_id') 
        ->withPivot(array('unit','amount')) 
        ->withTimestamps(); 
} 

主料:

public function recipes() { 
     return $this->belongsToMany('Recipe','ingredients_recipe','recipe_id','ingredients_id')->withPivot('amount'); 
} 
public function lists() { 
     return $this->belongsToMany('ShoppingList','shopping_list_ingredients','shopping_list_id','ingredients_id') 
     ->withPivot(array('unit','amount')) 
     ->withTimestamps(); 
} 

我在做什么错?谢谢!

回答

1

您的解释与此代码有点混淆,但重点是,您需要找到缺少的成分并将它们添加到购物清单中,这是正确的吗?

为此,您可以使用收集的差异方法:

// retrieve collection of the ingredients for a recipe 
$recipe = Recipe::with('ingredients')->find($recipeId); 

// retrieve collection of the ingredients for a shopping list 
$list = ShoppingList::with('ingredients')->find($recipeId); 

// find the ingredients for the recipe that are not on the list already 
// return Collection of Ingredient models 
$missingIngredients = $recipe->ingredients->diff($list->ingredients); 

// and ingredients on both list and recipe 
$missingIngredients = $recipe->ingredients->intersect($list->ingredients); 
+0

yes和no。我需要找到配料,这些配料已经在用户的购物清单中。比方说,配方有3种成分(香肠,奶酪,面包)。用户用奶酪和香肠创建了一个列表。所以需要知道,哪些ID已经在列表中(成分 - >添加= 1或0)。那个更好吗? :) – Marek123

+0

acutally是你所做的相同的代码,但只是改变变量,对吧? – Marek123

+0

如果您需要查找列表和配方中的成分,请使用交叉方法代替差异 –