简体   繁体   English

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

[英]Return the last record in a One to many Eloquent Relation using Laravel

Assuming there existed a One To Many relation where a User has Many Jobs, and the last record in the job table is the current job of the user.假设存在One To Many关系,其中一个用户有多个作业, job表中的最后一条记录是用户的当前作业。 What is a better way of returning the users with their last jobs?有什么更好的方法可以让用户返回上一次工作?

Here is what I have tried.这是我尝试过的。

User Class

public function ejob(){
   return $this->hasMany(Ejob::class);
}

Ejob Class

public function user(){
   return $this->belongsTo(User::class);
}

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() ));
}

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'
        ];
}

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'),
        ];
    }

Currently, this returns a user with all related records from the ejobs table but I want just the last job.目前,这会从ejobs表中返回一个包含所有相关记录的用户,但我只想要最后一个作业。

You could define another relationship method for the same relationship but define it as a Has One instead of a Has Many:您可以为相同的关系定义另一种关系方法,但将其定义为 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
}

Then you could eager load that instead of the ejob relationship where needed.然后你可以在需要的地方急切加载它而不是ejob关系。

You can use first() instead of get() .您可以使用first()而不是get() So it'll get a single model instance.所以它会得到一个单一的模型实例。 get() method give a collection and first() method give you a single model instance. get()方法给出一个集合,而first()方法给出一个单一的模型实例。

User::with(
          $this->particulars()
        )->orderBy('id', 'desc')->first()

Or you can use latest() to get the last inserted record.或者您可以使用latest()获取最后插入的记录。

User::with(
          $this->particulars()
        )->latest()->first()

->latest() fetches the most recent set of data from the Database. ->latest()从数据库中获取最新的数据集。 In short, it sorts the data fetched, using the created_at column to chronologically order the data.简而言之,它对获取的数据进行排序,使用created_at列按时间顺序排列数据。

Edit:-编辑:-

As you wanted to get the last record of the relationship you can do as below.由于您想获得关系的最后记录,您可以按如下方式进行。

User::with('ejob', function($query) {
    return $query->latest()->first();
})->get();
// 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();
}

You can group it by GROUP BY and then return all results.您可以按 GROUP BY 对其进行分组,然后返回所有结果。 There you will see job for each User在那里你会看到每个用户的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM