简体   繁体   中英

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. Then I want to save the following array in laravel at once:

$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.

Is there any simple way of doing that in Laravel?

You may try this when creating a single Category to attach with new Post :

$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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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