当前位置:网站首页>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()) {
//
}
以后就这么判断是否为空了!

边栏推荐
- Sensitive information leakage
- (1) the print () function, escape character, binary and character encoding, variables, data type, the input () function, operator
- Summary of php function vulnerabilities
- 对账、结账、错账更正方法、划线更正法、红字更正法、补充登记法
- PHP Foundation March Press Announcement Released
- Cookie is used to collect the admin privileges CTF foundation problem
- 利用cookie获取admin权限 CTF基础题
- 云安全笔记:云原生全链路加密
- 【无标题】
- 如何一步一步的:玩转全民拼购!
猜你喜欢

链动2+1模式开发系统

一个网络安全小白鼠的学习之路—nmap高级用法之脚本使用

(1) print()函数、转义字符、二进制与字符编码 、变量、数据类型、input()函数、运算符

hackmyvm: controller walkthrough

DVWA drone installation tutorial

12. What is JS

会计凭证概述、原始凭证、原始凭证的种类、原始凭证的基本内容、原始凭证的填制要求、原始凭证的审核

Solve the problem of Zlibrary stuck/can't find the domain name/reached the limit, the latest address of Zlibrary

hackmyvm-random walkthrough

GreenOptic: 1 vulnhub walkthrough
随机推荐
CTF entry md5
账务处理程序、记账凭证账务处理程序、汇总记账凭证账务处理程序、科目汇总表账务处理程序、会计信息化概述、信息化环境下会计账务处理的基本要求(此章出1道小题)
PHP反序列化漏洞
After Alibaba Cloud sets up domain name resolution redirection, I cannot use Chrome to access it
CTF-网鼎杯往届题目
重点考:从债劵的角度来看交易性金融资产
对账、结账、错账更正方法、划线更正法、红字更正法、补充登记法
DNS详解
DVWA drone installation tutorial
CTF入门之md5
PHP realizes the automatic reverse search prompt of the search box
hackmyvm: controller walkthrough
管理会计(对内)指引、管理会计要素及其具体内容(可能考,考前记一下,推荐记一下四个大点即可)、
利用cookie获取admin权限 CTF基础题
【泰山众筹】模式为什么一直都这么火热?是有原因的
政府会计的概念、政府会计标准体系、政府会计的特点(会形成小考点)、政府会计要素及其确认和计量、政府预算会计要素、政府财务会计要素
Activity
Scrapy crawler encounters redirection 301/302 problem solution
借贷记账法下的账户结构、借贷记账法的记账规则、借贷记账法下的账户对应关系与会计分录
一个网络安全小白鼠的学习之路—nmap高级用法之脚本使用