当前位置:网站首页>laravel数据库: 查询构造器
laravel数据库: 查询构造器
2022-08-08 16:28:00 【流火如夏xx】
数据库: 查询构造器
获取结果
- 从表中检索所有行
- get
use Illuminate\Support\Facades\DB;
$users = DB::table('users')->get();
//可以将列作为对象的属性来访问每列的值
foreach ($users as $user) {
echo $user->name;
}
- 从表中检索单行或单列
- first :检索单行
$user = DB::table('users')->where('name', 'John')->first();
return $user->email;
- value :提取单个值
$email = DB::table('users')->where('name', 'John')->value('email');
- find:通过 id 字段值获取单行数据
//()必填
$user = DB::table('users')->find(3);
- 获取某一列的值
pluck
- 包含单列值的集合
$titles = DB::table('users')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
- 第二个参数来指定结果集中要作为键的列
$titles = DB::table('users')->pluck('title', 'name');
foreach ($titles as $name => $title) {
echo $title;
}
聚合
- count, max, min, avg
- 判断记录是否存在
DB::table('orders')->where('finalized', 1)->count()
DB::table('orders')->where('finalized', 1)->exists()
DB::table('orders')->where('finalized', 1)->doesntExist()
Select 说明
自定义一个 「select」 查询语句来查询指定的字段
- select
$users = DB::table('users')
->select('name', 'email as user_email')
->get();
- distinct
$users = DB::table('users')->distinct()->get();
- addSelect
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
原生表达式
- raw
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
- selectRaw : 代替 addSelect(DB::raw(…))
$orders = DB::table('orders')
->selectRaw('price * ? as price_with_tax', [1.0825])
->get();
- whereRaw / orWhereRaw : 将原生的 「where」 注入到你的查询
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();
- havingRaw / orHavingRaw : 将原生字符串作为 「having」 语句的值
$orders = DB::table('orders')
->select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->get();
- orderByRaw : 将原生字符串设置为 「order by」 语句的值
$orders = DB::table('orders')
->orderByRaw('updated_at - created_at DESC')
->get();
- groupByRaw : 将原生字符串设置为 group by 语句的值
$orders = DB::table('orders')
->select('city', 'state')
->groupByRaw('city, state')
->get();
Joins
- Inner Join 语句
$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();
- Left Join / Right Join 语句
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
$users = DB::table('users')
->rightJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
- Cross Join 语句
$sizes = DB::table('sizes')
->crossJoin('colors')
->get();
- 高级 Join 语句
- 子连接查询
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
Unions
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();
Where语句
条件查询语句
- =
where('votes', '=', 100)
where('votes', 100)
- 其他操作符
where('votes', '>=', 100)
where('votes', '<>', 100)
where('name', 'like', 'T%')
- 条件数组
where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])
Or Where 语句
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
select * from users where votes > 100 or (name = ‘Abigail’ and votes > 50)
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere(function($query) {
$query->where('name', 'Abigail')
->where('votes', '>', 50);
})
->get();
Where Not 语句
“whereNot”和“orWhereNot”方法可用于否定给定的一组查询约束
$products = DB::table('products')
->whereNot(function ($query) {
$query->where('clearance', true)
->orWhere('price', '<', 10);
})
->get();
其他 Where 语句
- whereBetween / orWhereBetween / whereNotBetween / orWhereNotBetween
whereBetween('votes', [1, 100])
- whereIn / whereNotIn / orWhereIn / orWhereNotIn
whereIn('id', [1, 2, 3])
- whereNull / whereNotNull / orWhereNull / orWhereNotNull
whereNull('updated_at')
- whereDate / whereMonth / whereDay / whereYear / whereTime
whereDate('created_at', '2016-12-31')
whereMonth('created_at', '12')
whereDay('created_at', '31')
whereYear('created_at', '2016')
whereTime('created_at', '=', '11:20:45')
- whereColumn / orWhereColumn
whereColumn('first_name', 'last_name')
whereColumn('updated_at', '>', 'created_at')
whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at'],
])
逻辑分组
select * from users where name = ‘John’ and (votes > 100 or title = ‘Admin’)
$users = DB::table('users')
->where('name', '=', 'John')
->where(function ($query) {
$query->where('votes', '>', 100)
->orWhere('title', '=', 'Admin');
})
->get();
高级 Where 语句
WhereExists语句
$users = DB::table('users')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('orders')
->whereColumn('orders.user_id', 'users.id');
})
->get();
//select * from users
//where exists (
// select 1
// from orders
// where orders.user_id = users.id
//)
子查询 Where 语句
//子查询的结果与给定的值进行比较
$users = User::where(function ($query) {
$query->select('type')
->from('membership')
->whereColumn('membership.user_id', 'users.id')
->orderByDesc('membership.start_date')
->limit(1);
}, 'Pro')->get();
//构建一个“where”子句,将列与子查询的结果进行比较
$incomes = Income::where('amount', '<', function ($query) {
$query->selectRaw('avg(i.amount)')->from('incomes as i');
})->get();
Ordering, Grouping, Limit & Offset
- orderBy 方法
//要按多列排序,您可以根据需要多次调用 orderBy
orderBy('name', 'desc')
- latest 和 oldest 方法 : 默认根据数据表的 created_at 字段进行排序
$user = DB::table('users')
->latest()
->first();
- 随机排序
$randomUser = DB::table('users')
->inRandomOrder()
->first();
- 移除已存在的排序
$query = DB::table('users')->orderBy('name');
$unorderedUsers = $query->reorder()->get();
//传递一个列名和排序方式去重新排序整个查询:
$usersOrderedByEmail = $query->reorder('email', 'desc')->get();
分组
groupBy 和 having 方法
groupBy('account_id')
groupBy('first_name', 'status')
having('account_id', '>', 100)
havingBetween('number_of_orders', [5, 15])
边栏推荐
- 最稳定的淘宝商品详情接口
- OpenAI怎么写作「谷歌小发猫写作」
- 急了,Mysql索引中最不容易记的三个知识点通透了
- 基于LEAP模型的能源环境发展、碳排放建模预测及不确定性分析
- promise学习笔记
- 9. cuBLAS Development Guide Chinese Version--Configuration of Atomic Mode in cuBLAS
- Building and Visualizing Sudoku Games with Pygame
- bzoj1097 [POI2007]旅游景点atr
- 全网首发!消息中间件神仙笔记,涵盖阿里十年技术精髓
- 2020年适用于Linux的10个顶级开源缓存工具
猜你喜欢
谈谈怎么可以得到显著性图 特征图 featuremap
Web3构架是怎么样的?
[uniapp applet] view container cover-view
有了这个开源工具后,我五点就下班了!
基于ECS实现一分钟自动化部署【华为云至简致远】
开源项目管理解决方案Leantime
[Unity Starter Plan] Making RubyAdventure02 - Handling Tile Maps & Collision
jupyter notebook 隐藏&显示全部输出内容
ESP8266-Arduino编程实例-ADS1015(ADC)驱动
科创人·优锘科技COO孙岗:错误问题找不到正确答案,求索万物可视的大美未来
随机推荐
赶紧进来修内功!!!带你认识C语言中各种进制数和原码反码补码.
C#/VB.NET convert PDF to PDF/X-1a:2001
Node简介
C语言学习概览(四)
最新30系显卡搭建paddle飞浆环境|含CUDA下载安装
jupyter notebook hide & show all output
ctfshow七夕杯复现
国内部分手机游戏开始显示用户IP属地
浅学软件逆向笔记(2)
9. cuBLAS Development Guide Chinese Version--Configuration of Atomic Mode in cuBLAS
Redis design and implementation notes (1)
ggplot2可视化水平箱图并使用fct_reorder排序数据、使用na.rm处理缺失值(reorder boxplot with fct_reorder)、按照箱图的中位数从大到小排序水平箱图
在 Fedora 上使用 SSH 端口转发
耐心排序——专门快速解决最长递增子数组
国产数据库的红利还能“吃”多久?
腾讯云产品可观测最佳实践 (Function)
Groovy XML JSON
promise学习笔记
GPT3中文自动生成小说「谷歌小发猫写作」
IDEA2020安装教程