当数据库被播种时,是否可以阻止 Laravel 运行模型事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30492227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to prevent Laravel running Model Events when the database is being Seeded?
提问by Hyman
Laravel's seeder runs a variety of Model Events on my models which trigger New Order notification emails, among other things, from the Product::saved()
Model Event.
Laravel 的播种机在我的模型上运行各种模型事件,这些事件触发来自Product::saved()
模型事件的新订单通知电子邮件等。
This significantly slows down database seeding. Is it possible to detect whether a Seed is being ran and if so, tell Laravel not to run the Model Events?
这显着减慢了数据库播种。是否可以检测种子是否正在运行,如果是,告诉 Laravel 不要运行模型事件?
回答by user1669496
There are functions on the Model
class which will allow you to ignore events.
Model
类上有一些函数可以让您忽略事件。
Before using a model to seed, you will need to do something like this...
在使用模型播种之前,您需要执行以下操作...
YourModel::flushEventListeners();
回答by thisisablock
I recommend to remove the Dispatcher in this Case from the Eloquent Model.
我建议在这种情况下从 Eloquent 模型中删除 Dispatcher。
For example.
例如。
// Check Dispatcher
Model::getEventDispatcher()
// Remove Dispatcher
Model::unsetEventDispatcher()
// Add Dispatcher
Model::setEventDispatcher(new \Illuminate\Events\Dispatcher);