Laravel - whereHas 在不检查其他人的情况下检查关系

Laravel - whereHas checking latest record of a relationship without checking others(Laravel - whereHas 在不检查其他人的情况下检查关系的最新记录)
本文介绍了Laravel - whereHas 在不检查其他人的情况下检查关系的最新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有一对多关系的表.

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 在不检查其他人的情况下检查关系的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)