Laravel 9:如何在工厂definition方法中获取传入的属性
解决Laravel 9工厂中获取传入属性的问题
在Laravel 9的工厂定义方法中,要获取创建时传入的属性(如userable_type、userable_id),无需访问$this->states,直接通过$this->attributes即可拿到传入的属性数组。
修改UserFactory的definition方法,实现逻辑:如果创建工厂时传入了userable_type和userable_id,则直接使用这些值;否则继续随机生成关联模型。
修改后的UserFactory代码:
<?php namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class UserFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = User::class; /** * Define the model's default state. * * @return array */ public function definition() { // 检查是否传入了userable_type和userable_id if (isset($this->attributes['userable_type']) && isset($this->attributes['userable_id'])) { $userableType = $this->attributes['userable_type']; $userableId = $this->attributes['userable_id']; } else { // 没有传入则随机生成关联模型 $userableModel = (new $this->faker->userTypeModel)->factory()->create(); $userableType = $userableModel->getMorphClass(); $userableId = $userableModel->id; } return [ 'userable_type' => $userableType, 'userable_id' => $userableId, 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => bcrypt('admin1234'), // password 'remember_token' => Str::random(10) ]; } /** * Indicate that the model's email address should be unverified. * * @return \Illuminate\Database\Eloquent\Factories\Factory */ public function unverified() { return $this->state(function (array $attributes) { return [ 'email_verified_at' => null, ]; }); } }
关键说明
$this->attributes是Laravel工厂内置属性,存储了调用create()或make()时传入的所有属性。- 先判断目标属性是否存在,存在则直接取值;不存在则执行原随机生成逻辑,兼容两种使用场景。
内容的提问来源于stack exchange,提问作者abbasCoder51
相关产品推荐
相关产品推荐

