Synchronizing a one-to-many relationship in Laravel

后端 未结 5 597
Happy的楠姐
Happy的楠姐 2021-02-06 23:17

If I have a many-to-many relationship it\'s super easy to update the relationship with its sync method.

But what would I use to synchronize a one-to-many re

5条回答
  •  无人及你
    2021-02-06 23:52

    Unfortunately there is no sync method for one-to-many relations. It's pretty simple to do it by yourself. At least if you don't have any foreign key referencing links. Because then you can simple delete the rows and insert them all again.

    $links = array(
        new Link(),
        new Link()
    );
    
    $post->links()->delete();
    $post->links()->saveMany($links);
    

    If you really need to update existing one (for whatever reason) you need to do exactly what you described in your question.

提交回复
热议问题