問題描述
我有兩個具有一對多關系的表.
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模板網!