我正在尝试使用自定义Pivot模型,如:
class A extends Model{
public function b()
{
return $this->belongsToMany(B::class)
->using(PivotAB::class);
}
class PivotAB extends Pivot{}
通过关系访问PivotAB
时,数据透视表中的附加字段将丢失(从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
但是当我直接查询枢轴模型时,该字段会被填充:
>>> PivotAB::all();
=> Illuminate\Database\Eloquent\Collection {#1382
all: [
App\Models\PivotAB{#281
a_id: 1,
b_id: 1,
custom_field: "abc",
},
],
}
我错过了什么?我是否需要在某处声明透视字段?
我必须将所有字段添加到与->withPivot('custom_field')
的关系中,以便在通过A上的关系查询时填充它们。
不知怎的,我理解Laravel Docs要么必须使用->withPivot(...)
或->using(...)
,但实际上你需要包括两者。
谢谢@Sloothword!我遭受了同样错误的假设。 'withPivot','使用'和'as'都可以很好地协同工作。我最终成功使用了以下内容。
public function rosters(){
return $this->belongsToMany(Roster::class)
->withPivot('number','position')
->using(Membership::class)
->as("membership");
}