Laravel 5.8: Eloquent where 子句 returns null 但不执行 if..empty 条件

Laravel 5.8: Eloquent where clauses returns null but does not execute if..empty condition

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

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 的数据。

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

现在我为在 user_wallet table 上没有任何记录的用户测试这个,但它 returns 警告消息 User has the defined wallet 不知何故。

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

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

所以它似乎是空的。但是为什么不添加新记录到table?

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

在此处的代码中,您实际上从未使用过此集合中的任何内容,因为您只是在检查记录是否存在,看起来似乎存在。您应该使用查询生成器上的 exists 方法来执行检查是否存在的查询,这样您就不必 return 从未使用过的记录。

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

Laravel 5.8 Docs - Collections - Available Methods isEmpty

Laravel 5.8 Docs - Query Builder - Aggregates - Determining If Records Exist exists