简体   繁体   中英

Laravel belongsToMany() date desc

I use a belongsToMany() in Laravel, but a staff member can have more than one position, I want to bring the staff with the largest date and desc id.

PHP代码/ MySQL结果

In your Person.php , add a back relation to Position.php

public function positions()
{
  return $this->belongsToMany('Path\To\Person')->withPivot(['id', 'person_id', 'position_id', 'created_at', 'updated_at']);
}

Now you can do something like....

$positions = Person::positions()
                   ->wherePivot('action_date', '>=', $date)
                   ->orderBy('person_position.id', 'desc')
                   ->get();

$pivotTable = $positions->map(function($position) {
                return $position->pivot;
              });

Let me know if you face any other issue :)

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