问题描述
我有两个具有一对多关系的表.
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('AppBookingTask');
}
预订任务模型
public function booking() {
return $this->belongsTo('AppBooking');
}
我想获得预订清单,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 - whereHas 在不检查其他人的情况下检查关系的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!