![](/img/trans.png)
[英]Laravel: How to paginate eloquent “hasMany” relationship from Model class?
[英]How can I instantiate a new hasMany Eloquent relationship with at least one empty model?
我有一个具有hasMany
关系的模型(我们称其为PageModel
)(我们将其rulesList
)。 当我创建一个新的PageModel
,我想默认使用至少一个空模型的rulesList
。 我该如何在Eloquent中做到这一点?
代码示例:
// 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);
您必须创建此手动模型,然后将其添加到您的关系中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.