Php 如何在Laravel中一次保存阵列源中具有关系的模型
假设我有Post和Category模型,其中Post有多对多类别。然后我想立即在laravel中保存以下数组:Php 如何在Laravel中一次保存阵列源中具有关系的模型,php,laravel,relationship,Php,Laravel,Relationship,假设我有Post和Category模型,其中Post有多对多类别。然后我想立即在laravel中保存以下数组: $newPost = [ 'name' 'Some name of model', 'categories' => [ [ 'name' => 'The name of the new category without id' ], [ 'id' => 1,
$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中有什么简单的方法可以做到这一点吗?您可以在创建单个
类别
以附加新的帖子时尝试此方法:
$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));
查看更多信息