mysql - 在 Laravel eloquent 中执行“findManyOrCreate”需要最少的资源是什么?
问题描述
我有一组来自输入的邮政编码:
$postCodes = collect(["BK13TV", "BK14TV", "BK15TV", "BK16TV"]);
在我的数据库中,我已经有两个邮政编码——“BK13TV”、“BK16TV”。
所以我想运行这样的东西:
$postCodeModels = PostCode::findManyOrCreate($postCodes->map($postCode) {
return ['code' => $postCode]
})
我最初的方法是加载所有邮政编码,然后将它们与输入中的邮政编码进行比较,如下所示:
PostCode::createMany($postCodes->diff(PostCode::all()->pluck('code')))
但是,这意味着我正在加载 post_codes 表的全部内容,这似乎是错误的。
在理想情况下,这将返回与传递的邮政编码匹配的所有邮政编码模型,并为数据库中不存在的邮政编码创建条目。
解决方案
首先我需要检索现有的邮政编码:
$existingPostCodes = PostCode::whereIn('code', $postCodes)->get();
查找输入中尚未存储在数据库中的所有邮政编码:
$newPostCodes = $postCodes->diff($existingPostCode->pluck('code'));
最后检索所有新的邮政编码作为模型:
$postCodeModels = PostCode::whereIn('code', $postCodes)->get();
诚然,这仍然需要三个查询,但确实消除了加载整个表数据的疯狂事情。
推荐阅读
- mysql - Mysqldump - 选择数据库时出现错误 1049 unknown database [db]
- javascript - Javascript分号自动
- audio - 在 inno 设置中播放多声音的问题
- r - 如何在向量列表中分离粘贴
- .net - 即使未真正添加附件,Outlook 附件删除事件也会触发
- php - 如何为现有的 Wordpress 创建本地开发环境?
- php - 将下拉值插入数据库
- python - 即使经过大量检查和重新映射,if/else 语句也没有运行嵌入式代码
- php - 徽标的架构标记 [application/ld+json]
- r - 如何在R中按字母顺序对单个列进行排序?