我在控制器中尝试加载所有“成员”的以下代码。每个成员可以拥有多个电话号码。电话号码存储在名为phone_numbers
的表中,并与用户ID关联。在下面,我尝试加载为每个成员存储的最后一个电话号码。请注意,用户在手机上具有hasMany关系。
User.php
public function phone()
{
return $this->hasMany('App\Model\PhoneNumber');
}
这是我尝试过的:
$members = \App\Model\User::all();
$members->load('phone');
我感谢有关如何完成此操作的任何建议。
答案 0 :(得分:2)
要获取最新的行,您可以仅使用latest
,并使用hasOne
关系,如下所示:
public function phone()
{
return $this->hasOne('App\Model\PhoneNumber')->latest();
}
因此您可以为所有用户获取最新手机:
User::with('phone')->get();
答案 1 :(得分:0)
您可以这样做:
在您的用户模型中:
/**
* 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;
答案 2 :(得分:0)
我没有对其进行测试,但是您可以执行以下查询:
$members = User::with(['phone' => function($query) {
$query->orderBy('created_at', 'desc')->first();
}]);
这会将所有用户返回给您,但是连接了电话的用户只会创建最新的记录。