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();
}
我在做什麼錯?謝謝!
yes和no。我需要找到配料,這些配料已經在用戶的購物清單中。比方說,配方有3種成分(香腸,奶酪,麪包)。用戶用奶酪和香腸創建了一個列表。所以需要知道,哪些ID已經在列表中(成分 - >添加= 1或0)。那個更好嗎? :) – Marek123
acutally是你所做的相同的代碼,但只是改變變量,對吧? – Marek123
如果您需要查找列表和配方中的成分,請使用交叉方法代替差異 –