Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Laravel中一次保存阵列源中具有关系的模型_Php_Laravel_Relationship - Fatal编程技术网

Php 如何在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,

假设我有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中有什么简单的方法可以做到这一点吗?

您可以在创建单个
类别
以附加新的
帖子时尝试此方法:

$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));
查看更多信息