![](/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.