前言
在项目开发的过程中有时候需要进行数据库查询验证结果是否为空,不然后续操作会出现报错的问题。
//1.使用内置方法 isEmpty()
$userItems = User::where('id',1)->get();
if ($userItems->isEmpty()) {
}
//2.使用内置方法 count() 检查有没有记录
if (User::where('id',1)->count() > 0) {
}
//3.使用内置方法 exists() 建议使用该方法
$userItems = User::where('id',1)->get();
if ($userItems->exists()) {
//不为空
}
//4.使用内置方法 first()
$user = User::where('id',1)->first();
if ($user === null) {
//为空
}
//直接使用is_null()或empty()判段结果集是否为空。
$users = DB::table('user')->where('id', 1)->get();
//方法1
if($users){
//不为空
}
//方法2
if(is_null($users)){
//为空
}
//方法3
if(empty($users)){
//为空
}