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 ?
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.