当前位置:网站首页>laravel 查询数据库获取结果如何判断是否为空?
laravel 查询数据库获取结果如何判断是否为空?
2022-08-02 03:26:00 【陌潇】

laravel 查询数据库获取结果如何判断是否为空?
大家使用的场景是这样的:
$users = DB::table('users')->where('id',$id)->get();
if($users){
//有数据
}else{
//没数据
}
或
if(is_null($users)){
//
}
或
if(empty($users)){
//
}
以上方法都是不行的,在使用 Laravel Eloquent 模型时,我们要判断取出的结果集是否为空,但我们发现直接使用 is_null 或 empty是无法判段它结果集是否为空的!!!

var_dump 之后我们很容易发现,即使取到的空结果集,Eloquent 仍然会返回object(Illuminate\Support\Collection)对象实例。
其实,Eloquent 已经给我们封装几个判断方法如下:
$users = DB::table('users')->where('id',$id)->get();
if ($users->first()) {
//
}
if (!$users->isEmpty()) {
//
}
if ($users->count()) {
//
}
以后就这么判断是否为空了!

边栏推荐
猜你喜欢

file contains vulnerabilities

hackmyvm: again walkthrough

Alfa: 1 vulnhub walkthrough

CTF-Neting Cup Past Topics

Stable and easy-to-use short connection generation platform, supporting API batch generation

DVWA drone installation tutorial

链动2+1模式开发系统

Phonebook

xxe of CTF

Pycharm packages the project as an exe file
随机推荐
Masashi: 1 vulnhub walkthrough
Praying: 1 vulnhub walkthrough
3000字入门图神经网络
pytorch:保存和加载模型
PHP实现搜索框的自动反查提示
如何一步一步的:玩转全民拼购!
Phonebook
Anaconda报错:An unexpected error has occurred. Conda has prepared the above report 解决办法
重点考:从债劵的角度来看交易性金融资产
php函数漏洞总结
Basic use of v-on, parameter passing, modifiers
一个网络安全小白鼠的学习之路——nmap的基本使用
Warzone: 3 (Exogen) vulnhub walkthrough
利用cookie获取admin权限 CTF基础题
Smart Tips for Frida Scripting in Kali Environment
hackmyvm: controller walkthrough
c语言用栈实现计算中缀表达式
C language uses stack to calculate infix expressions
VIKINGS: 1 vulnhub walkthrough
4. The form with the input