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 方法,如下

复制代码
相关推荐
LearnYard1 分钟前
自然语言驱动的数据图表生成:几款工具功能对比实践
数据库·百度·powerpoint
一个有温度的技术博主26 分钟前
MySQL 三大日志协同机制:redo log、undo log 与 binlog 的联合运作
数据库·mysql·oracle
ltl42 分钟前
ClickHouse 与 DuckDB 选型:不是同一类列存
数据库
ltl1 小时前
RocksDB WAL 与 WriteBatch:持久化与原子批写
数据库
ltl1 小时前
流批一体与增量视图:Materialize、RisingWave 与 DBSP
数据库
ltl1 小时前
向量混合检索与标量过滤:表达式、bitset 与选择度
数据库
lf13210271 小时前
用 JSON Schema 管装修节点记录:从照片台账到可校验工程数据
网络·数据库·人工智能·经验分享·物联网·json·智能家居
AC赳赳老秦1 小时前
OpenClaw 多源采集公开行业数据:从原始信息到研究报告初稿的自动化实践
java·c语言·c++·python·php·deepseek·openclaw
roman_日积跬步-终至千里2 小时前
【资源控制】自助查询的智能路由
java·大数据·数据库
SelectDB2 小时前
无锡锡商银行 数据仓库演进:Apache Doris / SelectDB 的技术能力与实践
数据库