You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel在JSON循环中执行查询时即便记录不存在也始终返回存在

问题根源

你使用get()执行查询后返回的是 Laravel 集合对象 Illuminate\Database\Eloquent\Collection,哪怕查询结果没有匹配数据,这个集合对象本身也不是空值,用empty()判断会始终返回false,所以你永远得到“存在”的结果。
另外你原代码的闭包中引入了未使用的$value变量,属于冗余代码可以直接移除。

解决方法

有两种常用修正方案:

  • 方案1:使用集合自带的isEmpty()方法判断结果是否为空
// Get The Json From Source
$json = json_decode($request->getContent(), true);

// Loop Through Json And Insert Into Mysql
foreach ($json as $key => $value) {

    $result = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
        ->where(function ($q) use ($key) {
            $q->where('phone', $key)
                ->orWhere('email', $key);
        })->get();

    if ($result->isEmpty()) {
        echo "does-not-exist ";
    } else {
        echo "exists ";
    }
}
  • 方案2(更推荐,性能更好):直接使用exists()方法判断记录是否存在,不需要加载完整的查询结果,数据库层面直接返回布尔值
// Get The Json From Source
$json = json_decode($request->getContent(), true);

// Loop Through Json And Insert Into Mysql
foreach ($json as $key => $value) {

    $exists = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
        ->where(function ($q) use ($key) {
            $q->where('phone', $key)
                ->orWhere('email', $key);
        })->exists();

    if (!$exists) {
        echo "does-not-exist ";
    } else {
        echo "exists ";
    }
}

内容的提问来源于stack exchange,提问作者DragonFire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:21:01