我在拉拉维尔有个模特叫Player。此播放机数据是从外部API中提取的。我正在尝试从外部API中按计划更新这些外部数据。外部API数据是players表中应该包含的内容的权威来源。
我目前拥有两个集合,一个是来自数据库的数据,另一个是外部API数据。我基于API数据在集合中构建了新的Player模型。
我现在要说的是:
Collection $playersInDatabase; // Eloquent Collection of type Player
Collection $playersFromApi; // Collection of type Player$playersFromApi数据只是转换成新的播放器模型并添加到集合中的JSON数据。
我的问题是,我不能只是擦除整个players表,因为我一次只修改表的一个子集。有没有一种有效的方法来使用Laravel来比较这两种情况?我希望将任何新的播放器模型添加到不存在的数据库中,更新具有不同数据的现有播放机模型,然后删除API数据不再具有但仍在数据库中的任何记录(陈旧的记录)。
我能想到这样做的唯一方法是多次迭代集合以完成我想要做的事情,我觉得有一种更简单、更优雅的方法可以更好地利用框架。
作为参考,这里是players表的样子。我目前正在使用播种机数据:

发布于 2020-06-19 21:32:06
你可以这样做。不需要进行比较,只需在单个DB调用中为相应的派系删除任何in。
// the faction id you are querying from API
$faction_id = ...;
// for storing updated model ids
$updated_ids = [];
foreach ($playersFromApi as $playerFromApi) {
// update record or create a new one
$player = Player::updateOrCreate(
[
// conditions to meet
'...' => $playerFromApi['...']
],
[
// data to update
'...' => $playerFromApi['...']
]
);
// store id of updated model
$updated_ids[] = $player->id;
}
// delete models not updated
Player::where('faction_id',$faction_id)->whereNotIn('id',$updated_ids)->delete();https://stackoverflow.com/questions/62477830
复制相似问题