Laravel - 检查是否存在多对多的关系

时间:2014-04-14 16:10:34

标签: php laravel many-to-many relationship

用户可以将食材保存到购物清单中。现在,当用户登录并访问食谱时,购物清单小部件正在显示他,他已经在他的列表中有哪些成分,这就是我的问题。

在这里,我得到了食谱的所有成分:

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

在$ recipe->成分

上使用foreach正常工作

在这里,我正在获得用户对此食谱的购物清单,如果他有一个:

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 个答案:

答案 0 :(得分:1)

您的解释对此代码有点混浊,但关键是,您需要找到缺少的成分并将其添加到购物清单中,是否正确?

为此你可以使用Collection的diff方法:

// 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);