小编cod*_*ine的帖子

使用 Laravel 返回一对多雄辩关系中的最后一条记录

假设存在一个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)
    { …
Run Code Online (Sandbox Code Playgroud)

php laravel eloquent

7
推荐指数
3
解决办法
4947
查看次数

标签 统计

eloquent ×1

laravel ×1

php ×1