问题
The Problem
I can't make Laravel ignore fields that don't exist in the database when present in Eloquent's create
method or when seeding the database. In the example below, the "day" field does not exist in the Event table. However, I need it present in the array so I can use it in the EventObserver.php in order to create an $event->day at the same time as creating an $event. I realise I could create the Day
in it's own factory, I just want to know if this is possible or even advisable.
The error
Column not found: 1054 Unknown column 'day' in 'field list'
My Code
I am trying to attach an Observer method to my Event model that listens to the created
method so I can create a new object for each relationship. In my EventObserver, I have the following;
public function created(Event $event)
{
//get all attributes
$data = $event->getAttributes();
# fill any related models
$event->day->fill($data['day']);
# save event
$event->push();
}
In my Event Factory, I have this;
//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
]
];
});
Summary
How can I make Laravel ignore the day: []
property when creating an Event so I can still use it in the Observer?
回答1:
Eloquent doesn't store which columns exist in a table. Therefore, it will try to insert any fields you pass into the create method as long as they aren't blocked by the mass assignment protection.
One way to avoid this is to explicitly declare all fields in the $fillable property on your model. The mass assignment protection on the model will filter out all fields that don't exist in $fillable. This would prevent your observer from working properly since 'day' won't exist in the Model attributes.
In your case, you should never be creating the 'day' index in your EventFactory. Why would you create an index that doesn't exist in the factory for a model? There are much better ways to create related data, such as creating and using a different factory for the related models.
You can also create your own methods for creating and filling the model and related data. I wouldn't try to override the default create functionality.
来源:https://stackoverflow.com/questions/53118300/laravel-ignoring-fields-that-dont-exist-when-using-modelcreate