当前位置:网站首页>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()) {
//
}
以后就这么判断是否为空了!
边栏推荐
- hackmyvm-bunny预排
- php函数漏洞总结
- Praying: 1 vulnhub walkthrough
- 战场:3(双子叶植物)vulnhub走读
- (6) Design of student information management system
- 加密数字货币前传:从大卫·乔姆到中本聪
- 文件包含漏洞
- A network security guinea pig's learning path - scripting of advanced usage of nmap
- PHP realizes the automatic reverse search prompt of the search box
- 敏感信息泄露
猜你喜欢
(5) Modules and packages, encoding formats, file operations, directory operations
一个网络安全小白鼠的学习之路—nmap高级用法之脚本使用
(6) Design of student information management system
ES6 three-dot operator, array method, string extension method
file contains vulnerabilities
How to determine the direction based on two coordinate points on the map
hackmyvm: juggling walkthrough
xxe of CTF
hackmyvm: kitty walkthrough
hackmyvm: again walkthrough
随机推荐
web渗透必玩的靶场——DVWA靶场 1(centos8.2+phpstudy安装环境)
4. The form with the input
PALISADE:CKKS的使用
超级云APP,陪伴您一起成长的软件
Google Hacking
hackmyvm: controller walkthrough
How to determine the direction based on two coordinate points on the map
【无标题】
Eric target penetration test complete tutorial
OPENSSL基本实验以及OPENSSL详解
一个网络安全小白鼠的学习之路—nmap高级用法之脚本使用
Alfa: 1 vulnhub walkthrough
The first time to tear the code by hand, how to solve the problem of full arrangement
对账、结账、错账更正方法、划线更正法、红字更正法、补充登记法
cmake安装到指定目录
英语每日打卡
2. PHP variables, output, EOF, conditional statements
The learning path of a network security mouse - the basic use of nmap
A code audit notes (CVE - 2018-12613 phpmyadmin file contains loopholes)
GreenOptic: 1 vulnhub walkthrough