1.Laravel Eloquent模型
Eloquent 返回的所有后果集都是 Illuminate\Database\Eloquent\Collection 对象的实例,包含通过 get 办法检索或通过拜访关联关系获取到的后果。 Eloquent 的汇合对象继承了 Laravel 的 Base Collection,因而它天然也继承了数十种能优雅地解决 Eloquent 模型底层数组的办法。因而要判断数据存在,间接用内置办法即可。
<code class="php">// 1.应用内置办法 isEmpty() $userItems = User::where('sex', '=', '1')->get(); if ($userItems->isEmpty()) { } // 2.应用内置办法 count() 查看有没有记录 if (User::where('email', '=', $email)->count() > 0) { // 有记录 } // 3.应用内置办法 exists() 倡议应用该办法 $userItems = User::where('sex', '=', '1')->get(); if ($userItems->exists()) { // 有记录 } // 4.应用内置办法 first() $user = User::where('email', '=', $email)->first(); if ($user === null) { // 没记录 }
2.数据库:查问结构器
间接应用is_null()或empty()判段后果集是否为空。
<code class="php">$users = DB::table('users')->where('id', $id)->get(); // 办法1 if($users){ // 有记录 } // 办法2 if(is_null($users)){ // 没记录 } // 办法3 if(empty($users)){ // 没记录 }