简体   繁体   English

如何在Laravel中立即在数组源中保存具有关系的模型

[英]How to save model with relations in array source at once in Laravel

Suppose I have Post and Category models, which Post has many to many Categories. 假设我有Post和Category模型,其中Post具有许多类别。 Then I want to save the following array in laravel at once: 然后我想立即将以下数组保存在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'
        ]
    ]
];

when I use 当我使用

$newPostInstance = new Post();
$newPostInstance->fill($newPost);
$newPostInstance->save();

only the name property of the post is saved without categories data. 仅保存帖子的name属性,而不保存类别数据。

Is there any simple way of doing that in Laravel? 在Laravel中有什么简单的方法吗?

You may try this when creating a single Category to attach with new Post : 您可以在创建要与新Post附加的单个Category时尝试此操作:

$category = ['name' => 'The name of the new category without id'];
$newPostInstance = new Post()->fill($data);
$newPostInstance->categories()->save($category);

Or you may use something like this: 或者,您可以使用如下所示的内容:

$category1 = new Category;
$category1->name = 'CatOne';
$category1->save();

$category2 = new Category;
$category2->name = 'CatTwo';
$category2->save();

$newPostInstance->categories()->sync(array($category1->id, $category2->id));

Check more on documentation . 查看更多文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM