如何根据 Laravel 中的另一个集合比较和更新 Eloquent 集合
How to compare and update an Eloquent Collection based on another Collection in Laravel
我在 Laravel 中有一个名为 Player
的模型。该播放器数据是从外部 API 中提取的。我正在尝试从外部 API 定期更新此外部数据。外部 API 数据是 players
table.
中的权威来源
我目前有两个集合,一个是数据库中的数据,一个是外部的API数据。我根据 API 数据在集合中构建了新的 Player
模型。
我现在基本上拥有的是:
Collection $playersInDatabase; // Eloquent Collection of type Player
Collection $playersFromApi; // Collection of type Player
$playersFromApi
数据只是JSONAPI数据转换成新的Player模型并添加到集合中。
我的问题是我不能只擦除整个 players
table,因为我一次只修改 table 的一个子集。有没有一种有效的方法可以使用 Laravel 来比较这两者?我想将任何不存在的新播放器模型添加到数据库中,更新任何具有不同数据的现有播放器模型,然后还删除 API 数据不再具有但仍在数据库中的任何记录(陈旧的记录)。
我能想到的唯一方法是多次迭代集合以完成我想做的事情,我觉得有一种更简单、更优雅的方法可以更好地利用框架。
此处供参考的是 players
table 的样子。我目前正在使用播种机数据:
你可以这样做。无需比较,只需 updateOrCreate()
并删除任何未在单个数据库调用中为相应派系更新的 ID。
// 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();
我在 Laravel 中有一个名为 Player
的模型。该播放器数据是从外部 API 中提取的。我正在尝试从外部 API 定期更新此外部数据。外部 API 数据是 players
table.
我目前有两个集合,一个是数据库中的数据,一个是外部的API数据。我根据 API 数据在集合中构建了新的 Player
模型。
我现在基本上拥有的是:
Collection $playersInDatabase; // Eloquent Collection of type Player
Collection $playersFromApi; // Collection of type Player
$playersFromApi
数据只是JSONAPI数据转换成新的Player模型并添加到集合中。
我的问题是我不能只擦除整个 players
table,因为我一次只修改 table 的一个子集。有没有一种有效的方法可以使用 Laravel 来比较这两者?我想将任何不存在的新播放器模型添加到数据库中,更新任何具有不同数据的现有播放器模型,然后还删除 API 数据不再具有但仍在数据库中的任何记录(陈旧的记录)。
我能想到的唯一方法是多次迭代集合以完成我想做的事情,我觉得有一种更简单、更优雅的方法可以更好地利用框架。
此处供参考的是 players
table 的样子。我目前正在使用播种机数据:
你可以这样做。无需比较,只需 updateOrCreate()
并删除任何未在单个数据库调用中为相应派系更新的 ID。
// 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();