0

I have the following User and Order table.

User

enter image description here

Order

enter image description here

And I have defined one to many relationship in a User model as,

protected $primaryKey = 'user_id';
public function orders() {
    return $this->hasMany(Order::class, 'user_id');
}

Now I am trying to get the orders based on a particular user whose user_id is '1'.

$orders = App\User::find(1)->orders;

I have two modifications here.

  1. I have added protected $primaryKey = 'user_id'; in User Model.
  2. I had to add 'user_id' parameter as $this->hasMany(Order::class, 'user_id')

Now the question is that I want to know if the above modifications are correct to reflect the proper relationship and get the proper data as mentioned in the following code.

$orders = App\User::find(1)->orders;

P.S. I have just started to explore the Laravel.

Dushyant Joshi
  • 3,672
  • 3
  • 28
  • 52

0 Answers0