Laravel-在不检查他人的情况下检查关系的最新记录的地方 [英] Laravel - whereHas checking latest record of a relationship without checking others
问题描述
我有两个具有一对多关系的表.
I have two tables that has One to Many relationship.
预订-(id)
booking_tasks-(id, booking_id,user_id)
booking_tasks - (id, booking_id,user_id)
一个预订有很多任务 一个任务有一个预订
one booking has many task one task has one booking
预订模式:
public function tasks() {
return $this->hasMany('App\BookingTask');
}
BookingTask模型
BookingTask Model
public function booking() {
return $this->belongsTo('App\Booking');
}
我想获取预订清单, user_id = 2,表示最近的预订任务.我不想检查其他旧的booking_tasks.
I want to get list of bookings that, user_id = 2 for latest booking_task for the bookings. I do not want to check other old booking_tasks of the bookings.
例如:
我想检查booking_task的user_id = 2的最后一条记录是否可以作为预订. 在示例中,最后一个booking_task的user_id =5.因此,它将不会作为预订.
I want to check whether the last record of the booking_task's user_id=2 then get it as a booking. In the example last booking_task's user_id = 5. So it will not get as booking.
我的代码是:
$bookings=Booking::whereHas('tasks',function($q){
$q->where('user_id',2);//this will check whether any of record has user_id =2
})->get();
我也使用了这个: 但这不是正确的,
I used this also: But it is not a correct one,
$bookings=Booking::whereHas('tasks',function($q){
$q->latest()->where('user_id',2)->limit(1);//this will check whether any of record has user_id =2 and return latest one.
})->get();
我该如何解决这个问题,我也必须使用Laravel Eloquent.
Ho can I solve this problem, I have to use Laravel Eloquent also.
推荐答案
这需要更复杂的查询:
$bookings = Booking::select('bookings.*')
->join('booking_tasks', 'bookings.id', 'booking_tasks.booking_id')
->where('booking_tasks.user_id', 2)
->where('booking_tasks.id', function($query) {
$query->select('id')
->from('booking_tasks')
->whereColumn('booking_id', 'bookings.id')
->latest()
->limit(1);
})->get();
这篇关于Laravel-在不检查他人的情况下检查关系的最新记录的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!