I am trying to use a custom Pivot Model like:
class A extends Model{
public function b()
{
return $this->belongsToMany(B::class)
->using(PivotAB::class);
}
class PivotAB extends Pivot{}
When accessing PivotAB
through the relationship the additional field from the pivot table is missing (output from artisan tinker
):
>>>$q = A::all();
=> Illuminate\Database\Eloquent\Collection {#1385
all: [
App\Models\A {#1386
id: 1
},
],
}
>>> $q[0]->b[0]->pivot;
=> App\Models\PivotAB {#1389
a_id: 1,
b_id: 1,
}
>>> $q[0]->b[0]->pivot->custom_field;
=> null
But when i query the pivot model directly the field gets populated:
>>> PivotAB::all();
=> Illuminate\Database\Eloquent\Collection {#1382
all: [
App\Models\PivotAB{#281
a_id: 1,
b_id: 1,
custom_field: "abc",
},
],
}
What am i missing? Do i need to declare the pivot fields somewhere?
I had to add all fields to the relationship with ->withPivot('custom_field')
, so they get populated when querying via the relationship on A.
Somehow i understood the Laravel Docs as either having to use ->withPivot(...)
or ->using(...)
, but actually you need to include both.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments