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



我有一个模型(我们称之为PageModel)具有hasMany关系(我们称之为rulesList)。当我创建一个新PageModel时,我想默认rulesList至少有一个空模型。我怎样才能在雄辩中做到这一点?

代码示例:

// 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

(据我所知)在关系本身中没有一种方法可以做到这一点。原因是雄辩模型是由数据库查询返回值定义的。

您可以在数据库中设置某种空行,但我建议不要这样做。

一种可能有效的方法:我认为可以在不运行查询的情况下创建一个雄辩的模型。我认为像EloquentModel::fill($attributes)这样的事情会做到。其中$attributes是模型的属性数组,例如 array('title' => null, 'description' => null);

您必须创建此手动模型,然后将其添加到您的关系中。

最新更新