Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Define Relations and Get All Records with Relations in Laravel?

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?

like image 498
Mehdi Alikhani Avatar asked Sep 12 '25 04:09

Mehdi Alikhani


1 Answers

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');
} 
like image 157
sabbir chowdury Avatar answered Sep 14 '25 17:09

sabbir chowdury