I have three models
A user created a meeting and other members are invited to that meeting
I need to get the meeting with the detail of the user who created the meeting for the user that is invited to that meeting
So I have an meeting table
Model Meeting
function creator() {
return $this->belongsTo( 'User', 'created_by' );
}
function attendees() {
return $this->hasMany('MeetingAttendees');
}
Model User
function invitedMeetings() {
return $this->hasMany( 'MeetingAttendees' );
}
Model Meeting Attendees
function meeting() {
return $this->belongsTo('Meeting');
}
and finally the code to load the relation. where $user
is the User Object
$user->invitedMeetings()
->with(['meeting.creator' => function ($query) use ($status) {
if (!empty($status)) {
$query->where('meetings.status', '=', $status);
}
}])->get();
I need to get only meetings where the $status
has a certain value, but the where is adding a query to user table. I cannot seem to add a where in the relation load. How can I achieve this?
You should be able to do this much easier
$user->invitedMeetings()
->with(['meeting', 'meeting.creator'])
->where('status', '=', 'accepted')
->get()
//If you want to do a check on another table
$user->invitedMeetings()
->with(['meeting', 'meeting.creator'])
->where('meeting.status', '=', 'accepted')
->get()
Have a look here to get a better understanding about nesting eloquent relations: Eloquent Nested Relation with Some Constraint
I have figured out the answer for this, so
$user->invitedMeetings()
->with(['meeting.creator' => function ($query) use ($status) {
if (!empty($status)) {
$query->where('meetings.status', '=', $status);
}
}])->get();
should be changed to
$user->invitedMeetings()
->with(['meeting' => function ($query) use ($status) {
$query->where('meetings.status', '=', $status)->with('creator');
}])->get();
This solved my issue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.