Laravel 8 Pivot (中轉(zhuǎn)) 表屬性

2021-07-26 09:34 更新

如果需要定義應(yīng)該在鏈接模型的中轉(zhuǎn)表 / 中間表上設(shè)置的屬性,可以使用「hasAttached」方法。此方法接受中轉(zhuǎn)表屬性名稱和值的數(shù)組作為其第二個(gè)參數(shù):

    use App\Models\Role;
    use App\Models\User;

    $users = User::factory()
                ->hasAttached(
                    Role::factory()->count(3),
                    ['active' => true]
                )
                ->create(); 

如果您的狀態(tài)更改需要訪問相關(guān)模型,則可以提供基于閉包的狀態(tài)轉(zhuǎn)換:

    $users = User::factory()
                ->hasAttached(
                    Role::factory()
                        ->count(3)
                        ->state(function (array $attributes, User $user) {
                            return ['name' => $user->name.' Role'];
                        }),
                    ['active' => true]
                )
                ->create(); 
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)