I want to define a relationship between tables, and I don't know where I'm going wrong.
These are my tables:
users
-id -email -level
restaurants
-id -name -user_id
menus
-id -name
restaurant_menu
-restaurant_id -menu_id -price
In the users
table, the field level
will set by me with two words: [user]
or [restaurant]
.
User Model
public function restaurant(){
return $this->hasOne(Restaurant::class);
}
Restaurant Model
public function menus(){
return $this->hasMany(Menu::class);
}
Menu Model
public function restaurants(){
return $this->belongsTo(Restaurant::class);
}
I expect the output of this code:
$result = $restaurant->where('id',2)->menus()->get();
To be records and relations, but i get the following error.
BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Builder::menus()
What should I do?
IN user model
public function restaurant(){
return $this->hasMany(Restaurant::class,'user_id','id');
}
Restaurant model
public function menus(){
return $this->hasMany(Menu::class,'id','menu_id');
}
Menu model
public function restaurants(){
return $this->belongsTo(Restaurant::class);
}
As you aspect your output you need to write
$result = Restaurant::with('menus')->where('id',2)->get();
you will get relational data. Like which restaurants has which menus.
You also can use this for your scenario. Use this in your Restaurant model
public function menues(){
return $this>hasManyThrough(Menu::class,restaurant_menu::class,'menu_id','id','id','restaurant_id');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With