[英]Using a where condition in multtiple relation eager load in laravel
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
是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. 我只需要获得$status
具有特定值的会议,但是在哪里向用户表添加查询。 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 这解决了我的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.