php - PHP - Laravel userstamps不干扰数据库种子设置

我现在的方式:


class ClientObserver


{


 public function creating(Client $client)


 {


 $client->author()->associate(auth()->user());


 }


}




$factory->define(Client::class, function (Faker $faker) {


 return [


 'name' => $faker->company,


 'description' => $faker->paragraph,


 'address' => $faker->address,


 'created_by' => User::all()->random()->id,


 ];


});



我得到一个错误:


Integrity constraint violation: 19 NOT NULL constraint failed: clients.created_by



有没有办法阻止观察者采取行动?

谢谢:

时间:


// DatabaseSeeder.php


public function run()


{


 config()->set('seeding', true);



 factory(AppClient::class, 50)->create();



 config()->set('seeding', false);


}



通过重写模型的boot方法,可以避免使用Observer,检查config值,并根据需要设置用户。


// Client.php


protected static function boot() {


 parent::boot();



 static::creating(function($client) {


 if (config()->get('seeding') === true)


 auth()->setUser(User::inRandomOrder()->first());


 $client->author()->associate(auth()->user());


 });


}



...