I have a model (let's call it PageModel
) with a hasMany
relationship (let's call it rulesList
). When I create a new PageModel
, I want to default rulesList
with at least one empty model. How can I do this in Eloquent?
Code Sample:
// Normal instantiation
$this->rulesList; // Equals NULL
// I can set it manually like so, but is that right?
$this->rulesList = Collection::make([new RulesListModel]);
// NOTE: Doing this does not create an empty model when PageModel is output as JSON
There isn't (to my knowledge) a way to do this within the relationship itself. The reason is that an eloquent model is defined by the database query return values.
You could set up some sort of null row in your database, but I would advise against that.
One way that may work: I think it is possible to create an eloquent model without running a query. I think something like EloquentModel::fill($attributes)
would do it. Where $attributes
is an array of attributes for your model eg array('title' => null, 'description' => null);
You'd have to create this manual model and then add it to your relationship.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.