简体   繁体   中英

Laravel Eloquent get last pivot record within Model method

As in the title, is it possible to achieve something like this?

class Sign extends Eloquent
{
   public function lastStatus()
   {
      return $this->belongsToMany(Status::class)
                  ->withPivot('timestamp')
                  ->orderBy('timestamp', 'desc')
                  ->take(1);
   }
}

There is many-to-many relationship between sign and status , I've got pivot table sign_status . Every assignment in sign_status has its timestamp , so I can get information about the last status, but how to achieve this within Model method?

It is necessary to do it in this way, because then I will build a query like:

Gantry::whereHas('sign.lastStatus', function($q){...});

And i will filter by status which is an error to get gantries which at least one sign has error - but I need to search for that error in the last statuses of each sign.

Thanks!

我认为应该是$this->hasMany(Status::class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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