问题
当Eloquent的create
方法中存在种子数据库时,我不能使Laravel忽略数据库中不存在的字段。在下面的示例中,“日期”字段在事件表中不存在。但是,我需要它存在于数组中,以便可以在EventObserver.php中使用它,以便在创建$ event的同时创建$ event-> day。我意识到我可以在自己的工厂中创建Day
,我只想知道这是可能的还是建议的。
错误
找不到列:1054“字段列表”中的未知列“ day”
我的代码
我试图将Observer方法附加到侦听created
方法的Event模型上,以便为每个关系创建一个新对象。在我的EventObserver中,我有以下内容;
public function created(Event $event)
{
//get all attributes
$data = $event->getAttributes();
# fill any related models
$event->day->fill($data['day']);
# save event
$event->push();
}
在我的活动工厂中,我有这个;
//EventFactory.php
$factory->define(App\Event::class, function (Faker $faker) {
return [
"name" => "A Test Event",
"description" => $faker->paragraphs(3, true),
"event_start_date" => today(),
"event_opening_date" => today(),
"event_closing_date" => tomorrow(),
"user_id" => 1,
"banner_id" => 1,
"gallery_id" => 1,
"related_event_id" => 1,
"status" => "published",
"purchase_limit" => 1000,
"limit_remaining" => 1000,
"delivery_method" => "collection",
"merchandise_delivery_method" => "collection",
"day" => [
"event_id" => 1,
"name" => "Created with observer",
"date" => today(),
"ticket_limit" => 1000,
"limit_remaining" => 1000
]
];
});
摘要
在创建事件时如何使Laravel忽略day: []
属性,以便我仍然可以在Observer中使用它?
答案 0 :(得分:2)
Eloquent不存储表中存在哪些列。因此,它将尝试将您传递的所有字段插入到create方法中,只要它们不受批量分配保护的阻止即可。
避免这种情况的一种方法是在模型的 $ fillable 属性中显式声明所有字段。模型上的质量分配保护将过滤出$ fillable中不存在的所有字段。由于Model属性中将不存在“ day”,因此这将阻止您的观察者正常工作。
就您而言,您永远不应在EventFactory中创建“ day”索引。为什么要创建模型的工厂中不存在的索引?创建相关数据的方法要好得多,例如为相关模型创建和使用其他工厂。
您还可以创建自己的方法来创建和填充模型及相关数据。我不会尝试覆盖默认的创建功能。