【问题标题】:Laravel 5.8: Eloquent where clauses returns null but does not execute if..empty conditionLaravel 5.8:雄辩的 where 子句返回 null 但不执行 if..empty 条件
【发布时间】:2021-10-17 16:20:14
【问题描述】:

我有一个这样的控制器方法:

public function postNewWallet(Request $request, $user)
    {
        $find = UserWallet::where('user_id',$user)->where('wallet_id', $request->wallet_choose)->get();
        // dd($find);
        if(empty($find)){
            UserWallet::create([
                'user_id' => $user,
                'wallet_id' => $request->wallet_choose,
                'balance' => 0
            ]);

            flash()->overlay('Submitted', 'Information submitted', 'success');
        }else{
            flash()->overlay('Warning!', 'User has the defined wallet', 'warning');
        }

        return redirect()->back();
    }

所以我添加了两个where 子句来检查$useruser_id$request->wallet_choosewallet_id 是否存在任何数据。

然后如果$find 返回空,则添加一条新记录。否则显示警告warning 消息。

现在我为在user_wallet 表上没有任何记录但它以某种方式返回警告消息User has the defined wallet 的用户进行测试。

但是,如果我取消注释 dd($find),我会得到以下结果:

Illuminate\Database\Eloquent\Collection {#2551 ▼
  #items: []
}

所以它似乎是空的。但是为什么不向表中添加新记录呢?

【问题讨论】:

    标签: php laravel eloquent laravel-5.8


    【解决方案1】:

    empty($collection) 将始终返回 false。如果您想知道某个集合是否为空,请致电 isEmpty()$collection->isEmpty()。您也可以在查询生成器上调用first() 而不是get() 来尝试检索第一条记录而不是所有记录; first() 返回模型实例或 null,这将与您的 empty($result) 检查一起使用。

    在您的代码中,您实际上从未使用过此集合中的任何内容,因为您只是在检查记录是否存在。您应该使用 Query Builder 上的 exists 方法来执行检查是否存在的查询,这样您就不必返回从未使用过的记录。

    $exists = UserWallet::where('user_id', $user)
        ->where('wallet_id', $request->wallet_choose)
        ->exists(); 
    // $exists is a bool
    

    Laravel 5.8 Docs - Collections - Available MethodsisEmpty

    Laravel 5.8 Docs - Query Builder - Aggregates - Determining If Records Existexists

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 2018-05-19
      • 2021-02-13
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2020-12-15
      相关资源
      最近更新 更多