【发布时间】:2014-05-28 16:48:14
【问题描述】:
用户可以将食材保存到购物清单中。现在,当用户登录并访问食谱时,购物清单小部件会向他显示他的清单上已经有哪些成分,这就是我的问题。
我在这里获取食谱的所有成分:
$recipe = Recipe::find($id);
$recipe->load('ingredients');
在 $recipe->ingredients 上使用 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();
}
我做错了什么?谢谢!
【问题讨论】:
标签: php laravel many-to-many relationship