简体   繁体   中英

How to join only last record of the table in laravel?

I have two tables beneficiaries and accommodation_histories and I want only to join last record of accommodation_histories into beneficiaries .

This is my method so far:

public function getQuery(): Builder
{
    return DB::table('beneficiaries')
        ->select([
            'beneficiaries.id',
            'media.id as media',
            'beneficiaries.name as beneficiary_name',
            'beneficiaries.surname',
            'beneficiaries.gender',
            'beneficiaries.date_of_birth',
            'countries.name as country_of_birth',
            'accommodation_histories.center as center',
            'accommodation_histories.date_of_receipt as date_of_receipt',
            'accommodation_histories.release_date as release_date',
        ])
        ->leftJoin('media', 'media.model_id', '=', 'beneficiaries.id')
        ->join('countries', 'countries.id', '=', 'beneficiaries.country_of_birth')
        ->join('accommodation_histories', 'accommodation_histories.beneficiary', '=', 'beneficiaries.id');
}

You can do something like below at the parent model (beneficiaries):

public function accommodation_histories()
{
    return $this->hasOne('App\Accommodation_histories')->orderBy('id', 'desc');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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