Reputation: 3798
I have following tables,
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?
Upvotes: 0
Views: 53
Reputation: 1491
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
Upvotes: 1