Maidul I
Maidul I

Reputation: 332

How to call eager loading on a column other than user?

I have Review and User models. In the User modal, I have hasMany('App\Review') and in the Reviews model I have belongsTo('App\User'). I call this:

Review::where('user_id', $user)->with('user')->paginate(4);

This works and I get the user who wrote the review and the review itself:

However, in the Reviews table, I also have the person who they reviewed (called fulfiller_id). I want to load each review with the user who got reviewed. I did something like this:

Review::where('user_id', $user)->with('fulfiller_id')->paginate(4);

but that gives me an error:

Call to undefined relationship [fulfiller_id] on model [App\Review].

How do I go about also attaching the user under the fulfiller_id along with each review?

Upvotes: 0

Views: 44

Answers (1)

Jeff
Jeff

Reputation: 25221

you can make a second relationship on the Review model:

Review.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function fulfiller()
{
    return $this->belongsTo(User::class, 'fulfiller_id');
}

Then you can load:

Review::where('user_id', $user)->with(['user','fulfiller'])->paginate(4);

Upvotes: 2

Related Questions