Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading last record of hasMany relationship

I have the following code in my controller where I am trying to load all 'members'. Every member can have more than one phone number. Phone numbers are stored in a table called phone_numbers and are tied to user id's. Below, I am trying to load the last phone number stored for every member. Note, the user has a hasMany relationship on the phone.

User.php

public function phone()
{
    return $this->hasMany('App\Model\PhoneNumber');
}

This is what I tried:

$members = \App\Model\User::all();
$members->load('phone');

I appreciate any suggestions on how to accomplish this.

like image 696
AnchovyLegend Avatar asked Dec 17 '22 13:12

AnchovyLegend


1 Answers

To get the latest row, you can just use latest, and use hasOne relationship like this:

public function phone()
{
    return $this->hasOne('App\Model\PhoneNumber')->latest();
}

So you can get the latest phone for all users:

User::with('phone')->get();
like image 198
TsaiKoga Avatar answered Jan 13 '23 19:01

TsaiKoga