加载 hasMany 关系的最后一条记录
Loading last record of hasMany relationship
我的控制器中有以下代码,我试图在其中加载所有 'members'。每个成员可以拥有多个 phone 号码。 Phone 号码存储在名为 phone_numbers
的 table 中,并与用户 ID 相关联。下面,我试图加载为每个成员存储的最后一个 phone 号码。注意,用户在 phone.
上有 hasMany 关系
User.php
public function phone()
{
return $this->hasMany('App\Model\PhoneNumber');
}
这是我试过的:
$members = \App\Model\User::all();
$members->load('phone');
对于如何完成此任务的任何建议,我都很感激。
您可以通过以下方式实现:
在您的用户模型中:
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['last_phone'];
protected function getLastPhoneAttribute()
{
return $this->phone()->orderBy('created_at')->first();
}
use App\Model\User;
$lastPhones = User::all()->map->last_phone;
要获取最新行,您可以只使用 latest
,并使用 hasOne
关系,如下所示:
public function phone()
{
return $this->hasOne('App\Model\PhoneNumber')->latest();
}
因此您可以获得所有用户的最新 phone:
User::with('phone')->get();
我的控制器中有以下代码,我试图在其中加载所有 'members'。每个成员可以拥有多个 phone 号码。 Phone 号码存储在名为 phone_numbers
的 table 中,并与用户 ID 相关联。下面,我试图加载为每个成员存储的最后一个 phone 号码。注意,用户在 phone.
User.php
public function phone()
{
return $this->hasMany('App\Model\PhoneNumber');
}
这是我试过的:
$members = \App\Model\User::all();
$members->load('phone');
对于如何完成此任务的任何建议,我都很感激。
您可以通过以下方式实现:
在您的用户模型中:
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['last_phone'];
protected function getLastPhoneAttribute()
{
return $this->phone()->orderBy('created_at')->first();
}
use App\Model\User;
$lastPhones = User::all()->map->last_phone;
要获取最新行,您可以只使用 latest
,并使用 hasOne
关系,如下所示:
public function phone()
{
return $this->hasOne('App\Model\PhoneNumber')->latest();
}
因此您可以获得所有用户的最新 phone:
User::with('phone')->get();