当前位置:网站首页>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: kitty walkthrough
- 一次代码审计的笔记(CVE-2018-12613 phpmyadmin文件包含漏洞)
- hackmyvm-random walkthrough
- Phonebook
- VIKINGS: 1 vulnhub walkthrough
- 一个网络安全小白鼠的学习之路——nmap的基本使用
- php函数漏洞总结
- (7) superficial "crawlers" process (concept + practice)
- 会计凭证概述、原始凭证、原始凭证的种类、原始凭证的基本内容、原始凭证的填制要求、原始凭证的审核
- 借贷记账法下的账户结构、借贷记账法的记账规则、借贷记账法下的账户对应关系与会计分录
猜你喜欢

How to log in to Alibaba Cloud server using the admin account
![[sebastian/diff] A historical change extension library for comparing two texts](/img/c7/ea79db7a5003523ece7cf4f39e4987.png)
[sebastian/diff] A historical change extension library for comparing two texts

hackmyvm-random walkthrough

ES6 array extension methods map, filter, reduce, fill and array traversal for…in for…of arr.forEach

强化学习笔记:DDPG

redis未授权访问(4-unacc)

GreenOptic: 1 vulnhub walkthrough

重点考:从债劵的角度来看交易性金融资产

uniapp | Compilation error after updating with npm update

CTF entry md5
随机推荐
pytorch:保存和加载模型
文件上传漏洞
Eric靶机渗透测试通关全教程
Pycharm packages the project as an exe file
元宇宙:为何互联网大佬纷纷涉足?元宇宙跟NFT是什么关系?
The first time to tear the code by hand, how to solve the problem of full arrangement
重点考:金融资产概述、交易性金融资产的概念、交易性金融资产的账务处理(取得、持有。出售)、
16. JS events, string and operator
How to determine the direction based on two coordinate points on the map
什么是广告电商商业模式?这几个门派告诉你
广告电商「私域打工人」职业前景:你离月薪6万,还差多远?
12. What is JS
Introduction to PHP (self-study notes)
PHP deserialization vulnerability
(6) Design of student information management system
CTF entry md5
17. JS conditional statements and loops, and data type conversion
Cookie is used to collect the admin privileges CTF foundation problem
文件包含漏洞
(7) superficial "crawlers" process (concept + practice)