您可以使用UPSERT 插入或更新重复键,也可以使用关系。
这意味着您可以将旧数据与新数据进行比较,并使用包含要更新的数据的数组以及要插入到同一查询中的数据。
您也可以删除其他不需要的 id。
这里是一个例子:
$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
);
这将创建下一个查询:
delete from
`links`
where
`links`.`post_id` = 247
and `links`.`post_id` is not null
and `id` not in (56, 57, 58)
还有:
insert into
`links` (`id`, `link`, `input`)
values
(57, '...', '...'),
(58, '...', '...'),
(null, '...', '...')
on duplicate key update
`link` = values(`link`),
`input` = values(`input`)
这就是您可以在 2 个查询中更新关系的所有元素的方法。例如,如果您有 1,000 个帖子,并且您想要更新所有帖子的所有链接。