首页 > 解决方案 > 在 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 表的全部内容,这似乎是错误的。

在理想情况下,这将返回与传递的邮政编码匹配的所有邮政编码模型,并为数据库中不存在的邮政编码创建条目。

标签: mysqllaraveleloquent

解决方案


首先我需要检索现有的邮政编码:

$existingPostCodes = PostCode::whereIn('code', $postCodes)->get();

查找输入中尚未存储在数据库中的所有邮政编码:

$newPostCodes = $postCodes->diff($existingPostCode->pluck('code'));

最后检索所有新的邮政编码作为模型:

$postCodeModels = PostCode::whereIn('code', $postCodes)->get();

诚然,这仍然需要三个查询,但确实消除了加载整个表数据的疯狂事情。


推荐阅读