Laravel常用数据库操作指令(模型/DB)

1、使用模型操作数据库,需要先引入相应的模型

如:use App\Models\Test;

2、使用DB操作数据库需要先引入DB库

如:use Illuminate\Support\Facades\DB;

一、数据库查询操作

get方法:

复制代码
写法一:Test::select('id','name')->where('id','=',1)->get();//select可以单独查询某几列字段

写法二:Test::where('id','=',1)->get();//去除select后默认去除该表的所有字段

如果上面使用DB类操作,只需要改成:DB::table('name')->where('id','=',1)->get();

DB类操作,遍历值只能是:

复制代码
$v->name;exit;

而模型类操作遍历都可以:

复制代码
$v->name;或者$v['name'];

first方法 ->first():

获取的是单个的集合非数组类的

value方法 :value('name')

方法从纪录中提取单个值

常用的聚合函数:

count()、max()、avg()、min()

existsdoesntExist 查询结果是否存在

distinct ()去重

连表查询:

$users = DB::table('users')

->join('contacts', 'users.id', '=', 'contacts.user_id')

->join('orders', 'users.id', '=', 'orders.user_id')

->select('users.*', 'contacts.phone', 'orders.price')

->get();

where 语句:

第一个值为名称、第二个为操作符号,第三个为值

如果只有两个字段。where会默认使用=号。

常用的where操作运算符:=、>、<、<>、like、

$users = DB::table('users')

->where('votes', '=', 100)

->where('age', '>', 35)

->get();

orWhere():代表或or的关系

闭包

$users = DB::table('users')

->where('votes', '>', 100)

->orWhere(function(Builder query) { query->where('name', 'Abigail')

->where('votes', '>', 50);

})

->get();

select * from users where votes > 100 or (name = 'Abigail' and votes > 50)

Where Not

下面的查询排除了正在清仓甩卖或价格低于

$products = DB::table('products')

->whereNot(function (Builder query) { query->where('clearance', true)
->orWhere('price', '<', 10);
})
->get();

whereBetween / orWhereBetween

whereBetween 方法是用来验证字段的值是否在给定的两个值之间

$users = DB::table('users')

->whereBetween('votes', [1, 100])

->get();

whereNotBetween / orWhereNotBetween

whereIn 方法用于验证字段是否在给定的值数组中

$users = DB::table('users')

->whereIn('id', [1, 2, 3])

->get();

$users = DB::table('users')

->whereNotIn('id', [1, 2, 3])

->get();

whereNull 方法用于判断指定的字段的值是否是 NULL

$users = DB::table('users')
->whereNull('updated_at')
->get();

whereNotNull 方法是用来验证给定字段的值是否不为 NULL:

whereDate / whereMonth / whereDay / whereYear / whereTime

$users = DB::table('users')

->whereDate('created_at', '2016-12-31')

->get();

$users = DB::table('users')

->whereMonth('created_at', '12')

->get();

whereColumn 方法是用来比较两个给定字段的值是否相等:

inRandomOrder 方法被用来将查询结果随机排序。例如,你可以使用这个方法去获得一个随机用户

latestoldest 方法可以方便让你把结果根据日期排序。查询结果默认根据数据表的 created_at

如你所愿,groupByhaving 方法可以将查询结果分组。having 方法的使用方法类似于 where 方法

​​​​​​​

或者,你可以使用 limitoffset 方法。这些方法在功能上等同于 takeskip 方法,如下

复制代码
相关推荐
施嘉伟1 小时前
一次生产环境 SQL 不走索引的排查过程
数据库·sql
踏浪无痕2 小时前
SQLInsight:从JDBC底层到API调用的零侵入SQL监控方案
数据库·后端·开源
小宇的天下2 小时前
Calibre nmDRC Results(19-1)
服务器·数据库·oracle
siner.li2 小时前
laravel的Redis锁实现
laravel
桃花键神2 小时前
Undetectable接入亮数据代理IP深度测评:高效、稳定、适配性极强的海外多账号运营利器
网络协议·tcp/ip·php
Web项目开发3 小时前
Mysql创建索引的SQL脚本,复制粘贴即可使用
数据库·sql·mysql
catchadmin3 小时前
PHP 8.5 #[\NoDiscard] 揪出“忽略返回值“的 Bug
php
晴天¥3 小时前
Oracle如何在DBeaver上进行登录
数据库·oracle
2301_800256113 小时前
事务处理-同步与调度-两阶段锁-隔离级别
数据库·oracle
小罗和阿泽3 小时前
MySql数据库系列 数据库基础操作
数据库·mysql