Synchronizing a one-to-many relationship in Laravel

后端 未结 5 592
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-07 00:13

    You can use UPSERT to insert or update on duplicate key, also using relations.

    That means that you can comper your old data with your new data, and use an array with the data to be updated with the data to be inserted in the same query.

    Also you can delete other ids that are not needed.

    Here an example:

        $toSave = [
            [
                'id'=>57,
                'link'=>'...',
                'input'=>'...',
            ],[
                'id'=>58,
                'link'=>'...',
                'input'=>'...',
            ],[
                'id'=>null,
                'link'=>'...',
                'input'=>'...',
            ],
        ];
    
        // Id of models you wish to keep
        // Keep existing that dont need update
        // And existing that will be updated
        // The query will remove the rest from the related Post
        $toKeep = [56,57,58];
    
    
        // We skip id 56 cause its equal to existing
        // We will insert or update the rest
    
        // Elements in $toSave without Id will be created into the relationship
    
        $this->$relation()->whereNotIn('id',$toKeep)->delete();
    
        $this->$relation()->upsert(
            $toSave,            // Data to be created or updated
            ['id'],             // Unique Id Column Key
            ['link','input']    // Columns to be updated in case of duplicate key, insert otherwise
        );
    

    That will create the next queries:

    delete from
      `links`
    where
      `links`.`post_id` = 247
      and `links`.`post_id` is not null
      and `id` not in (56, 57, 58)
    

    And:

    insert into
      `links` (`id`, `link`, `input`)
    values
      (57, '...', '...'),
      (58, '...', '...'),
      (null, '...', '...')
      on duplicate key update
      `link` = values(`link`),
      `input` = values(`input`)
    

    This is how you can update all elements of a relationship in just 2 queries. For example if you have 1,000 Posts, and you want to update all the links of all the posts.

提交回复
热议问题