简体   繁体   中英

How to create extra relation in pivot table in laravel

I have following tables,

  • users -> id
  • diplomas -> id
  • diploma_user -> id, user_id, diploma_id, invoice_id
  • invoices -> id

I can get the diplomas of users by defining this relation in User class.

public function diplomas(){
   return $this->belongsToMany(Diploma::class);
}

How I can get diplomas of users with the invoices? $user->diploma->pivot->invoice ?

You need to define an extra pivot model that holds the relation: https://laravel.com/docs/9.x/eloquent-relationships#defining-custom-intermediate-table-models

public function diplomas(){
   return $this
        ->belongsToMany(Diploma::class)
        ->using(DiplomaUser::class)
        ->withPivot('invoice_id');
}

and your DiplomaUserClass:

class DiplomaUser extends Pivot
{
    public function invoice() {
        return $this->belongsTo(Invoice::class)
    }
}

Now you can do $user->diplomas->first()->pivot->invoice

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