简体   繁体   English

Laravel 5雄辩地从相关表中获取记录

[英]Laravel 5 Eloquent getting records from related tables

I'm new to laravel and I'm using Laravel 5.2 I want to have the record of the maximum end date in a bookings columns of a perticular request. 我是laravel的新手,正在使用Laravel 5.2,我想在一个特定请求的预订列中记录最大结束日期。 My tables are like : 我的桌子就像:

request
-----------
id | name
----------
1   | My request

bookings
-----------
id | request_id | start_date | end_date
--------------------------------------------
1   | 1         | 2016-03-01 | 2016-03-05
2   | 1         | 2016-03-10 | 2016-03-20
3   | 1         | 2016-03-25 | 2016-03-28

Request Model
------------------
public function bookings()
{
    return $this->hasMany( 'App\Booking' );
}

I want to have the request data with the maximum end date ( for the example above the record will be booking Id : 3 ). 我想要具有最大结束日期的请求数据(对于上面记录中的示例将是预订ID:3)。 Please help. 请帮忙。

I've tried the following : 我尝试了以下方法:

$request = \DB::table( 'requests' )
                ->join( 'bookings', 'requests.id', '=', 'bookings.request_id' )
                ->where( 'requests.id', 1 )
                ->max( 'bookings.end_date' );

But I wonder how to do this with eloquent. 但是我不知道该如何雄辩地做到这一点。

您可以在该日期之前按降序排列并选择第一条记录:

$request = Request::find(1)->bookings()->orderBy('end_date', 'DESC')->first();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM