[英]Laravel Model: how to get all relations as array with custom array keys?
[英]How to save model with relations in array source at once in Laravel
假設我有Post和Category模型,其中Post具有許多類別。 然后我想立即將以下數組保存在laravel中:
$newPost = [
'name' 'Some name of model',
'categories' => [
[
'name' => 'The name of the new category without id'
],
[
'id' => 1,
'name' => 'The name of the exists category'
]
]
];
當我使用
$newPostInstance = new Post();
$newPostInstance->fill($newPost);
$newPostInstance->save();
僅保存帖子的name屬性,而不保存類別數據。
在Laravel中有什么簡單的方法嗎?
您可以在創建要與新Post
附加的單個Category
時嘗試此操作:
$category = ['name' => 'The name of the new category without id'];
$newPostInstance = new Post()->fill($data);
$newPostInstance->categories()->save($category);
或者,您可以使用如下所示的內容:
$category1 = new Category;
$category1->name = 'CatOne';
$category1->save();
$category2 = new Category;
$category2->name = 'CatTwo';
$category2->save();
$newPostInstance->categories()->sync(array($category1->id, $category2->id));
查看更多文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.