简体   繁体   English

我如何用至少一个空模型实例化一个新的hasMany Eloquent关系?

[英]How can I instantiate a new hasMany Eloquent relationship with at least one empty model?

I have a model (let's call it PageModel ) with a hasMany relationship (let's call it rulesList ). 我有一个具有hasMany关系的模型(我们称其为PageModel )(我们将其rulesList )。 When I create a new PageModel , I want to default rulesList with at least one empty model. 当我创建一个新的PageModel ,我想默认使用至少一个空模型的rulesList How can I do this in Eloquent? 我该如何在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. 我认为类似EloquentModel::fill($attributes)可以做到。 Where $attributes is an array of attributes for your model eg array('title' => null, 'description' => null); 其中$attributes是模型的属性数组,例如array('title' => null, 'description' => null);

You'd have to create this manual model and then add it to your relationship. 您必须创建此手动模型,然后将其添加到您的关系中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM