【问题标题】:Laravel Query Inside Json LoopJson 循环内的 Laravel 查询
【发布时间】:2021-11-09 08:44:12
【问题描述】:

在 json 循环中查询总是返回存在,即使行不存在。

嗨,我有一个像这样的 Json 对象

{"+888588888":"Person 1", "some_mail@gmail.com":"Person 2"}

我正在使用下面的代码来检查表中是否存在记录:

    // 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, $value) {
                $q->where('phone', $key)
                    ->orWhere('email', $key);
            })->get();

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

我总是存在

【问题讨论】:

  • 您期望结果是什么?只有一个?多个?
  • 每个键的结果
  • 这是检查一个用户吗?那你为什么要使用循环而不是 WHERE IN
  • 是的,一个用户使用
  • 在这种情况下,您可以在一个查询中完成,而不是使用 foreach 循环。你只使用数组中的键,所以使用array_keys($json)whereIn() 旁注:在编程时考虑使用好的变量名:你有一个变量$json 包含一个数组。这令人困惑:-)

标签: php json laravel


【解决方案1】:

$result 永远不会“空”!!即使没有返回记录,它仍然是 Collection::class 的实例,其中包含空数组作为项目。

你应该在$result->count()(集合类的一个方法)上进行测试

或改进您的代码。

foreach ($json as $key => $value) {
    $count = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
        ->where(function ($q) use ($key, $value) {
            $q->where('phone', $key)
                ->orWhere('email', $key);
        })->count(); //return an integer

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

如果您需要用户实体,请先使用

foreach ($json as $key => $value) {
    $user = UserInvitesModel::where('mysql_user_id', $mysql_user_id)
        ->where(function ($q) use ($key, $value) {
            $q->where('phone', $key)
                ->orWhere('email', $key);
        })->first(); //returns null or an instance of the model

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

【讨论】:

  • var_dump($user);给出 NULL... 所以使用 is_null($user) 它似乎正在工作,感谢您朝着那个方向推进
【解决方案2】:

您在集合上使用empty(),这就是问题所在。

您使用的->get() 方法返回一个集合,为了检查它是否至少有一个元素,您必须使用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, $value) {
                $q->where('phone', $key)
                    ->orWhere('email', $key);
            })->get();

        if ($result->isEmpty()) {
            echo "does-not-exist ";
        } else {
            echo "exists ";
        }
    }

empty() 总是在 Collection 上返回 false

empty(collect()); // false
collect()->isEmpty(); //true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多