cod*_*ine 7 php laravel eloquent
假设存在一个One To ManyUser有Many Jobs的关系,job表中最后一条记录就是该用户当前的job。有什么更好的方法可以让用户返回上一次工作?
这是我尝试过的。
User Class
public function ejob(){
return $this->hasMany(Ejob::class);
}
Run Code Online (Sandbox Code Playgroud)
Ejob Class
public function user(){
return $this->belongsTo(User::class);
}
Run Code Online (Sandbox Code Playgroud)
API Controller Method
public function index()
{
return UserResource::collection((
User::with(
$this->particulars() // I want the last record from this line
)->orderBy('id', 'desc')->get() ));
}
Run Code Online (Sandbox Code Playgroud)
Particulars Method
// I want the last record from this
private function particulars(){
return
[
'ejob.company:id,name',
'ejob.job:id,title',
'ejob.department:id,name',
'ejob.reporting:id,surname,first_name,other_name',
'ejob.employmentstatus:id,name',
'country:id,name',
'gender:id,name',
'state:id,name'
];
}
Run Code Online (Sandbox Code Playgroud)
User Resource
public function toArray($request)
{
//return parent::toArray($request);
return [
'data' => [
'id' => $this->id,
'surname' => $this->surname,
'first_name' => $this->first_name,
'other_name' => $this->other_name,
'email' => $this->email,
'phone_number' => $this->phone_number,
'birthday' => $this->birthday->format('d-m-Y'),
'age'=> $this->birthday->age,
'ejob' => $this->whenLoaded('ejob'),
];
}
Run Code Online (Sandbox Code Playgroud)
目前,这会返回一个包含ejobs表中所有相关记录的用户,但我只想要最后一份工作。
lag*_*box 11
您可以为相同的关系定义另一种关系方法,但将其定义为 Has One 而不是 Has Many:
public function currentJob()
{
return $this->hasOne(Ejob::class, ...)->latest();
// order by by how ever you need it ordered to get the latest
}
Run Code Online (Sandbox Code Playgroud)
然后你可以急切加载它而不是ejob需要的关系。
// in your case
public function currentJob()
{
return $this->hasOne(Ejob::class, ...)->latestOfMany();
// order by by how ever you need it ordered to get the latest
}
// another example
public function latestPerformance()
{
return $this->hasOne(Performance::class)->latestOfMany();
}
Run Code Online (Sandbox Code Playgroud)
您可以使用first()代替get(). 所以它将获得一个模型实例。
get()方法给出一个集合,first()方法给出一个模型实例。
User::with(
$this->particulars()
)->orderBy('id', 'desc')->first()
Run Code Online (Sandbox Code Playgroud)
或者您可以使用latest()来获取最后插入的记录。
User::with(
$this->particulars()
)->latest()->first()
Run Code Online (Sandbox Code Playgroud)
->latest()从数据库中获取最新的数据集。简而言之,它对获取的数据进行排序,使用created_at列按时间顺序对数据进行排序。
编辑:-
当您想获得关系的最后记录时,您可以执行以下操作。
User::with('ejob', function($query) {
return $query->latest()->first();
})->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4947 次 |
| 最近记录: |