Skip to content

Eloquent: 工廠

介紹

當測試您的應用程式或填充資料庫時,您可能需要向資料庫中插入一些記錄。Laravel 允許您為每個 Eloquent 模型 定義一組預設屬性,而不是手動指定每個欄位的值,這可以透過模型工廠來實現。

若要查看如何編寫工廠的範例,請查看應用程式中的 database/factories/UserFactory.php 檔案。此工廠包含在所有新的 Laravel 應用程式中,並包含以下工廠定義:

php
namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
 */
class UserFactory extends Factory
{
    /**
     * The current password being used by the factory.
     */
    protected static ?string $password;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     */
    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}

如您所見,工廠最基本的型式是繼承 Laravel 基礎工廠類別並定義 definition 方法的類別。definition 方法會返回在使用工廠建立模型時應應用的一組預設屬性值。

透過 fake 輔助函式,工廠可以存取 Faker PHP 函式庫,這讓您可以方便地生成各種隨機資料以進行測試和填充資料庫。

📌 備註

您可以透過更新 config/app.php 設定檔中的 faker_locale 選項來更改應用程式的 Faker 語系。

定義模型工廠

生成工廠

若要建立工廠,請執行 make:factory Artisan 指令

shell
php artisan make:factory PostFactory

新的工廠類別將會被放置在您的 database/factories 目錄中。

模型與工廠發現慣例

定義工廠後,您可以透過模型上 Illuminate\Database\Eloquent\Factories\HasFactory Trait 提供的靜態 factory 方法,為該模型實例化一個工廠實例。

HasFactory Trait 的 factory 方法將使用慣例來確定 Trait 所分配的模型之合適工廠。具體來說,該方法將在 Database\Factories 命名空間中尋找與模型名稱相符且以 Factory 為後綴的工廠類別。如果這些慣例不適用於您的特定應用程式或工廠,您可以覆寫模型上的 newFactory 方法以直接返回模型對應工廠的實例:

php
use Database\Factories\Administration\FlightFactory;

/**
 * Create a new factory instance for the model.
 */
protected static function newFactory()
{
    return FlightFactory::new();
}

然後,在對應的工廠上定義一個 model 屬性:

php
use App\Administration\Flight;
use Illuminate\Database\Eloquent\Factories\Factory;

class FlightFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var class-string<\Illuminate\Database\Eloquent\Model>
     */
    protected $model = Flight::class;
}

工廠狀態

狀態操作方法允許您定義可以任意組合應用於模型工廠的離散修改。例如,您的 Database\Factories\UserFactory 工廠可能包含一個 suspended 狀態方法,用於修改其預設屬性值之一。

狀態轉換方法通常會呼叫 Laravel 基礎工廠類別提供的 state 方法。state 方法接受一個閉包,該閉包將接收為工廠定義的原始屬性陣列,並應返回一個要修改的屬性陣列:

php
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * Indicate that the user is suspended.
 */
public function suspended(): Factory
{
    return $this->state(function (array $attributes) {
        return [
            'account_status' => 'suspended',
        ];
    });
}

「已刪除」狀態

如果您的 Eloquent 模型可以被 軟刪除,您可以呼叫內建的 trashed 狀態方法,以指示所建立的模型應該已經被「軟刪除」。您不需要手動定義 trashed 狀態,因為它會自動提供給所有工廠:

php
use App\Models\User;

$user = User::factory()->trashed()->create();

工廠回呼

工廠回呼是透過 afterMakingafterCreating 方法註冊的,它們允許您在實例化或創建模型之後執行額外任務。您應該透過在工廠類別上定義一個 configure 方法來註冊這些回呼。當工廠被實例化時,Laravel 將自動呼叫此方法:

php
namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    /**
     * Configure the model factory.
     */
    public function configure(): static
    {
        return $this->afterMaking(function (User $user) {
            // ...
        })->afterCreating(function (User $user) {
            // ...
        });
    }

    // ...
}

您也可以在狀態方法中註冊工廠回呼,以執行特定於給定狀態的額外任務:

php
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * Indicate that the user is suspended.
 */
public function suspended(): Factory
{
    return $this->state(function (array $attributes) {
        return [
            'account_status' => 'suspended',
        ];
    })->afterMaking(function (User $user) {
        // ...
    })->afterCreating(function (User $user) {
        // ...
    });
}

使用工廠建立模型

實例化模型

一旦您定義好工廠,便可使用 Illuminate\Database\Eloquent\Factories\HasFactory trait 提供給模型的靜態 factory 方法,以便為該模型實例化一個工廠實例。讓我們看看幾個建立模型的範例。首先,我們將使用 make 方法建立模型,但不將它們持久化到資料庫:

php
use App\Models\User;

$user = User::factory()->make();

您可以使用 count 方法建立多個模型的集合:

php
$users = User::factory()->count(3)->make();

應用狀態

您也可以將任何 工廠狀態 應用到模型上。如果您想對模型應用多個狀態轉換,可以直接呼叫狀態轉換方法:

php
$users = User::factory()->count(5)->suspended()->make();

覆寫屬性

如果您想覆寫模型的某些預設值,可以將一個值陣列傳遞給 make 方法。只有指定的屬性會被替換,而其餘屬性則保持工廠定義的預設值:

php
$user = User::factory()->make([
    'name' => 'Abigail Otwell',
]);

或者,可以直接在工廠實例上呼叫 state 方法,以執行行內狀態轉換:

php
$user = User::factory()->state([
    'name' => 'Abigail Otwell',
])->make();

📌 備註

使用工廠建立模型時,大量賦值保護 會自動停用。

持久化模型

create 方法會實例化模型實例,並使用 Eloquent 的 save 方法將它們持久化到資料庫:

php
use App\Models\User;

// Create a single App\Models\User instance...
$user = User::factory()->create();

// Create three App\Models\User instances...
$users = User::factory()->count(3)->create();

您可以透過將屬性陣列傳遞給 create 方法來覆寫工廠的預設模型屬性:

php
$user = User::factory()->create([
    'name' => 'Abigail',
]);

序列

有時您可能希望為每個建立的模型交替給定模型屬性的值。您可以透過將狀態轉換定義為序列來實現這一點。例如,您可能希望為每個建立的使用者,將 admin 欄位的值在 YN 之間交替:

php
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Sequence;

$users = User::factory()
    ->count(10)
    ->state(new Sequence(
        ['admin' => 'Y'],
        ['admin' => 'N'],
    ))
    ->create();

在此範例中,將建立五個 admin 值為 Y 的使用者,以及五個 admin 值為 N 的使用者。

如有必要,您可以將閉包作為序列值。每次序列需要新值時,該閉包都會被呼叫:

php
use Illuminate\Database\Eloquent\Factories\Sequence;

$users = User::factory()
    ->count(10)
    ->state(new Sequence(
        fn (Sequence $sequence) => ['role' => UserRoles::all()->random()],
    ))
    ->create();

在序列閉包中,您可以存取注入閉包的序列實例上的 $index 屬性。$index 屬性包含到目前為止序列已迭代的次數:

php
$users = User::factory()
    ->count(10)
    ->state(new Sequence(
        fn (Sequence $sequence) => ['name' => 'Name '.$sequence->index],
    ))
    ->create();

為了方便起見,也可以使用 sequence 方法來應用序列,該方法只是在內部呼叫 state 方法。sequence 方法接受閉包或序列化屬性陣列:

php
$users = User::factory()
    ->count(2)
    ->sequence(
        ['name' => 'First User'],
        ['name' => 'Second User'],
    )
    ->create();

工廠關聯

一對多關聯

接下來,讓我們使用 Laravel 流暢的工廠方法來探索建立 Eloquent 模型關聯。首先,假設我們的應用程式有一個 App\Models\User 模型和一個 App\Models\Post 模型。此外,假設 User 模型定義了與 PosthasMany 關聯。我們可以使用 Laravel 工廠提供的 has 方法來建立一個擁有三篇貼文的使用者。has 方法接受一個工廠實例:

php
use App\Models\Post;
use App\Models\User;

$user = User::factory()
    ->has(Post::factory()->count(3))
    ->create();

按照慣例,當將 Post 模型傳遞給 has 方法時,Laravel 會假設 User 模型必須有一個定義該關聯的 posts 方法。如有需要,你可以明確指定想要操作的關聯名稱:

php
$user = User::factory()
    ->has(Post::factory()->count(3), 'posts')
    ->create();

當然,你可以在相關模型上執行狀態操作。此外,如果你的狀態變更需要存取父模型,你可以傳遞一個基於閉包的狀態轉換:

php
$user = User::factory()
    ->has(
        Post::factory()
            ->count(3)
            ->state(function (array $attributes, User $user) {
                return ['user_type' => $user->type];
            })
        )
    ->create();

使用魔術方法

為了方便,你可以使用 Laravel 的魔術工廠關聯方法來建立關聯。例如,以下範例將會使用慣例來判斷相關模型應該透過 User 模型上的 posts 關聯方法來建立:

php
$user = User::factory()
    ->hasPosts(3)
    ->create();

當使用魔術方法建立工廠關聯時,你可以傳遞一個屬性陣列來覆寫相關模型上的屬性:

php
$user = User::factory()
    ->hasPosts(3, [
        'published' => false,
    ])
    ->create();

如果你的狀態變更需要存取父模型,你可以提供一個基於閉包的狀態轉換:

php
$user = User::factory()
    ->hasPosts(3, function (array $attributes, User $user) {
        return ['user_type' => $user->type];
    })
    ->create();

屬於關聯

既然我們已經探索了如何使用工廠建立「一對多」關聯,接下來讓我們探索關聯的反向。for 方法可用於定義工廠建立模型所屬的父模型。例如,我們可以建立三個屬於單一使用者的 App\Models\Post 模型實例:

php
use App\Models\Post;
use App\Models\User;

$posts = Post::factory()
    ->count(3)
    ->for(User::factory()->state([
        'name' => 'Jessica Archer',
    ]))
    ->create();

如果你已經有一個父模型實例,並且該實例應該與你正在建立的模型關聯,你可以將該模型實例傳遞給 for 方法:

php
$user = User::factory()->create();

$posts = Post::factory()
    ->count(3)
    ->for($user)
    ->create();

使用魔術方法

為了方便,你可以使用 Laravel 的魔術工廠關聯方法來定義「屬於」關聯。例如,以下範例將會使用慣例來判斷這三篇貼文應該屬於 Post 模型上的 user 關聯:

php
$posts = Post::factory()
    ->count(3)
    ->forUser([
        'name' => 'Jessica Archer',
    ])
    ->create();

多對多關聯

如同一對多關聯,「多對多」關聯也可以使用 has 方法建立:

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

$user = User::factory()
    ->has(Role::factory()->count(3))
    ->create();

樞紐表屬性

如果你需要定義應該在連結模型的樞紐表 / 中間表上設定的屬性,你可以使用 hasAttached 方法。此方法接受一個樞紐表屬性名稱和值的陣列作為其第二個參數:

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

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

如果你的狀態變更需要存取相關模型,你可以提供一個基於閉包的狀態轉換:

php
$user = User::factory()
    ->hasAttached(
        Role::factory()
            ->count(3)
            ->state(function (array $attributes, User $user) {
                return ['name' => $user->name.' Role'];
            }),
        ['active' => true]
    )
    ->create();

如果你已經有想要附加到正在建立的模型上的模型實例,你可以將這些模型實例傳遞給 hasAttached 方法。在這個範例中,相同的三個角色將會附加到所有三個使用者上:

php
$roles = Role::factory()->count(3)->create();

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

使用魔術方法

為了方便,你可以使用 Laravel 的魔術工廠關聯方法來定義多對多關聯。例如,以下範例將會使用慣例來判斷相關模型應該透過 User 模型上的 roles 關聯方法來建立:

php
$user = User::factory()
    ->hasRoles(1, [
        'name' => 'Editor'
    ])
    ->create();

多型關聯

多型關聯也可以使用工廠來建立。多型「morph many」關聯的建立方式與典型的「一對多」關聯相同。例如,如果 App\Models\Post 模型與 App\Models\Comment 模型有 morphMany 關聯:

php
use App\Models\Post;

$post = Post::factory()->hasComments(3)->create();

Morph To 關聯

魔術方法不能用於建立 morphTo 關聯。相反地,必須直接使用 for 方法,並且明確提供關聯的名稱。例如,想像 Comment 模型有一個定義 morphTo 關聯的 commentable 方法。在這種情況下,我們可以透過直接使用 for 方法來建立三個屬於單一篇貼文的評論:

php
$comments = Comment::factory()->count(3)->for(
    Post::factory(), 'commentable'
)->create();

多型多對多關聯

多型「多對多」(morphToMany / morphedByMany)關聯可以像非多型「多對多」關聯一樣建立:

php
use App\Models\Tag;
use App\Models\Video;

$video = Video::factory()
    ->hasAttached(
        Tag::factory()->count(3),
        ['public' => true]
    )
    ->create();

當然,魔術 has 方法也可以用於建立多型「多對多」關聯:

php
$video = Video::factory()
    ->hasTags(3, ['public' => true])
    ->create();

在工廠內定義關聯

若要在模型工廠中定義關聯,通常會將一個新的工廠實例指派給關聯的外鍵。這通常是針對像是 belongsTomorphTo 關聯這類型的「反向」關聯所做的。舉例來說,若您想在建立 Post 時建立一個新的 User,您可以這麼做:

php
use App\Models\User;

/**
 * Define the model's default state.
 *
 * @return array<string, mixed>
 */
public function definition(): array
{
    return [
        'user_id' => User::factory(),
        'title' => fake()->title(),
        'content' => fake()->paragraph(),
    ];
}

如果關聯的欄位依賴於定義它的工廠,您可以將一個 Closure 指派給屬性。該 Closure 會接收工廠已評估的屬性陣列:

php
/**
 * Define the model's default state.
 *
 * @return array<string, mixed>
 */
public function definition(): array
{
    return [
        'user_id' => User::factory(),
        'user_type' => function (array $attributes) {
            return User::find($attributes['user_id'])->type;
        },
        'title' => fake()->title(),
        'content' => fake()->paragraph(),
    ];
}

為關聯回收現有模型

如果您的模型與另一個模型共享共同關聯,您可以使用 recycle 方法,以確保相關模型的單一實例可被工廠建立的所有關聯重複使用。

舉例來說,假設您有 AirlineFlightTicket 模型,其中 Ticket 屬於 Airline 和 Flight,而 Flight 也屬於 Airline。建立 Ticket 時,您可能希望 Ticket 和 Flight 都使用相同的 Airline,因此您可以將一個 Airline 實例傳遞給 recycle 方法:

php
Ticket::factory()
    ->recycle(Airline::factory()->create())
    ->create();

如果您的模型屬於共同的 User 或 Team,您可能會發現 recycle 方法特別有用。

recycle 方法也接受一個現有模型的 Collection。當 recycle 方法提供了一個 Collection 時,當工廠需要該類型的模型時,會從該 Collection 中隨機選擇一個模型:

php
Ticket::factory()
    ->recycle($airlines)
    ->create();