Laravel 自定义数据透视模型缺少字段

Laravel Custom Pivot Model is missing fields

我正在尝试使用自定义数据透视模型,例如:

class A extends Model{
    public function b()
    {
        return $this->belongsToMany(B::class)
            ->using(PivotAB::class);
    }

class PivotAB extends Pivot{}

当通过关系访问 PivotAB 时,主元 table 的附加字段丢失(来自 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 文档理解为必须使用 ->withPivot(...)->using(...),但实际上您需要同时包含两者。

谢谢@Sloothword!我正遭受着同样错误的假设。 'withPivot'、'using' 和 'as' 可以很好地协同工作。我最终成功地使用了以下内容。

public function rosters(){
    return $this->belongsToMany(Roster::class)
                ->withPivot('number','position')
                ->using(Membership::class)
                ->as("membership");
}