我有两个具有一对多关系的表.
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 在不检查其他人的情况下检查关系的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Laravel 集合对象中添加新元素add new element in laravel collection object(在 Laravel 集合对象中添加新元素)
在 Laravel 5 中创建编辑模式Creating an edit modal in Laravel 5(在 Laravel 5 中创建编辑模式)
用于集合的 Laravel 5.5 API 资源(独立数据)Laravel 5.5 API resources for collections (standalone data)(用于集合的 Laravel 5.5 API 资源(独立数据))
在 php Laravel 5 中创建自定义辅助函数的最佳实践What is the best practice to create a custom helper function in php Laravel 5?(在 php Laravel 5 中创建自定义辅助函数的最佳实践是什么
没有“Access-Control-Allow-Origin"标头 - LaravelNo #39;Access-Control-Allow-Origin#39; header - Laravel(没有“Access-Control-Allow-Origin标头 - Laravel)
Laravel Passport Route 重定向到登录页面Laravel Passport Route redirects to login page(Laravel Passport Route 重定向到登录页面)