It doesnt work because you use a HasMany relation instead of a belongsToMany. You dont need the RecipeIngredient class.
Oct 12, 2015
9
Level 1
Relationships confusion
Hello. I having problems with Eloquent and I need some help.
I have 3 tables: Recipe, Ingredients, RecipeIngredients defined as follows
class Recipe extends Model {
protected $table = "recipes";
public function ingredients() {
return $this->hasMany(RecipeIngredient::class);
}
}
class RecipeIngredient extends Model
{
protected $table = "recipe_ingredients";
public function recipe() {
return $this->belongsTo(Recipe::class);
}
public function Ingredient() {
return $this->belongsTo(Ingredient::class);
}
}
class Ingredient extends Model
{
protected $table = "ingredients";
public function recipes() {
$this->hasMany(RecipeIngredient::class);
}
}
I am trying do to do
$recipe->ingredients()->associate($ingredient); // To associate an ingredient
$recipe->save();
I get the following error: Call to undefined method Illuminate\Database\Query\Builder::associate()
Why doesn't associate() work? Is this valid code?
I am trying to find the best way to sync (delete ingredients, and add ingredients) but I can't make it work. I tried sync() as well.
Please help.
Please or to participate in this conversation.