Laravel 模型读操作
来源:SegmentFault
2023-01-25 20:20:40
0浏览
收藏
在数据库实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Laravel 模型读操作》,聊聊MySQL、PHP、后端、lavarel,希望可以帮助到正在努力赚钱的你。
配套视频地址 https://www.bilibili.com/video/av70545323?p=6
创建模型
php artisan make:model User // 默认对应的表是 users
php artisan make:model AbCd // 默认对应的表是 ab_cds
/**
规则:
1. 除第一个大写字母,其他大写字母前都加上下划线
2. 所有的大写字母改成小写
3. 末尾加 s
*/
模型之读
\App\User::all(); // 返回包含所有对象的集合
\App\User::where('name', 'John')->first(); // 返回对象
\App\User::where('id', 1)->value('name'); // 返回值,例如 'leon'
\App\User::find(3); // 返回主键等于 3 的对象
\App\User::find([1, 2]); // 返回主键等于 1 和 2 的对象的集合
\App\User::pluck('age'); // 返回包含字段值的集合
\App\User::pluck('age', 'id'); // 返回关联集合 id => age,pluck 最多 2 个参数
\App\User::count(); // 返回记录总数
\App\User::max('id'); // 返回数字,库没有任何记录返回 null
\App\User::min('id'); // 返回数字,库没有任何记录返回 null
\App\User::avg('age'); // 返回数字,库没有任何记录返回 null,同名 averge
\App\User::sum('salary'); // 返回数字,库没有任何记录返回 0
where
where('votes', '=', 100)
where('votes', 100)
where('votes', '>=', 100)
where('votes', '', 100)
where('name', 'like', 'T%')
where([
['status', '=', '1'],
['subscribed', '', '1'],
])
where('votes', '>', 100)->orWhere('name', 'John')
whereBetween('votes', [1, 100]) // 包含了 1 和 100
whereNotBetween('votes', [1, 100])
whereIn('id', [1, 2, 3])
whereNotIn('id', [1, 2, 3])
whereNull('last_name')
whereNotNull('updated_at')
whereDate('created_at', '2016-12-31') // where date(created_at) = '2016-12-31')
whereMonth('created_at', '12')
whereDay('created_at', '31')
whereYear('created_at', '2016')
whereTime('created_at', '=', '11:20:45')
whereColumn('first_name', 'last_name') // 判断两个字段 相等
whereColumn('updated_at', '>', 'created_at')
whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at']
])
where('finalized', 1)->exists(); // 返回 true 或者 false
// select exists(select * from `xxx` where `finalized` = 1) as `exists`
where('finalized', 1)->doesntExist();
// 运行的 SQL 和上面的一样,Laravel 把运行结果取反就达成目的了
where('name', '=', 'John')
->orWhere(function ($query) { // 传入闭包进 orWhere,避免全局 scope 产生不良影响
$query->where('votes', '>', 100)
->where('title', '', 'Admin');
})
// where `name` = John or (`votes` > 100 and `title` Admin)
whereExists(function ($query) {
$query->selectRaw(1)
->from('orders')
->whereRaw('orders.user_id = users.id');
})
// where exists ( select 1 from orders where orders.user_id = users.id )
->whereRaw('price > IF(state = "TX", ?, 100)', [200])->get();
// IF 用法:IF(expr1,expr2,expr3)
// 如果 (expr1 0 and expr1 NULL),那么 expr1 就是 true。
json
$users = \App\User::where('options->language', 'en')
->get();
// select * from `users` where json_unquote(json_extract(`options`, '$."language"')) = 'en'
$users = \App\User::where('preferences->dining->meal', 'salad')
->get();
// select * from `users` where json_unquote(json_extract(`preferences`, '$."dining"."meal"')) = 'salad'
$users = \App\User::whereJsonLength('options->languages', 0)
->get();
// select * from `users` where json_length(`options`, '$."languages"') = 0
$users = \App\User::whereJsonLength('options->languages', '>', 1)
->get();
// select * from `users` where json_length(`options`, '$."languages"') > 1
\App\User::orderBy('date')->where('active', false)->chunk(100, function ($users) { // 取每 100 个一组
foreach ($users as $user) {
// ...
// return false; // 随时可以退出
}
});
// select * from `users` where `active` = 0 order by `date` asc limit 3 offset 0
// select * from `users` where `active` = 0 order by `date` asc limit 3 offset 3
// 注意,laravel 把 false 转化成了 0
// 不会出现 chunk 结束后,还有很多记录没被处理的情况
\App\User::where('active', false)->orderBy('date')
->chunkById(100, function ($users) {
foreach ($users as $user) {
\App\User::where('id', $user->id)
->update(['active' => true]);
}
});
// select * from `users` where `active` = 0 order by `date` asc, `id` asc limit 3
// select * from `users` where `active` = 0 and `id` > 3 order by `date` asc, `id` asc limit 3
select
$users = \App\User::select('name', 'email as user_email')->get();
$users = \App\User::distinct()->get();
// select distinct * from `users1`
$query = \App\User::select('name');
$users = $query->addSelect('age')->get();
// select `name`, `age` from `users`
->selectRaw('department, SUM(price) as total_sales')
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->orderByRaw('updated_at - created_at DESC')
->get();
// select department, SUM(price) as total_sales from `destinations` group by `department` having SUM(price) > 2500 order by updated_at - created_at DESC
join 和 union
# inner join
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
# left join
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
# right join
->rightJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
# cross join
->crossJoin('colours')
->get();
# 高级 join
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn('users.pid', '=', 'contacts.pid');
})
->get();
// select * from `users`
// inner join
// `contacts`
// on `users`.`id` = `contacts`.`user_id` or `users`.`pid` = `contacts`.`pid`
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
// select * from `users` inner join `contacts`
// on
// `users`.`id` = `contacts`.`user_id` and `contacts`.`user_id` > 5
# union
$first = App\User::whereNull('first_name');
$users = App\Student::whereNull('last_name')
->union($first)
->get();
// (select * from `students` where `last_name` is null) union (select * from `users` where `first_name` is null)
# unionAll 和 union 参数一样
// unionAll 不会去除重复值
排序、分组和分页
orderBy('name', 'desc')
latest() // === orderBy('created_at', 'desc')
inRandomOrder()
// order by RAND()
->groupBy('account_id')->having('account_id', '>', 100)
->groupBy('site', 'qianjinyike.com')->having('account_id', '>', 100)
skip(10)->take(5) // 等价于 offset(10)->limit(5)
// limit 5 offset 10
分支执行 sql
// $role 有值才会执行闭包
$role = $request->input('role');
$users = \App\User::when($role, function ($query) use ($role) {
return $query->where('role_id', $role);
})
->get();
// $role 有值执行第一个闭包,否则执行第二个闭包
$sortBy = null;
$users = \App\User::when($sortBy, function ($query, $sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();
刷新模型
$flight = App\Flight::where('number', 'FR 900')->first();
$freshFlight = $flight->fresh(); // 去数据库里面重新取了一次
$flight = App\Flight::where('number', 'FR 900')->first();
$flight->number = 'FR 456';
$flight->refresh();
$flight->number; // "FR 900"
游标
foreach (Flight::where('foo', 'bar')->cursor() as $flight) {
//
}
$users = App\User::cursor()->filter(function ($user) {
return $user->id > 500;
});
高级子查询
Destination::addSelect(['last_flight' => Flight::select('name')
->whereColumn('destination_id', 'destinations.id')
->orderBy('arrived_at', 'desc')
->latest()
->limit(1)
])->get();
// select `destinations`.*, (select `name` from `flights` where `destination_id` = `destinations`.`id` order by `arrived_at` desc, `created_at` desc limit 1) as `last_flight` from `destinations`
未找到异常
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
全局作用域
// 可以自由在 app 文件夹下创建 Scopes 文件夹来存放
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class AgeScope implements Scope {
public function apply(Builder $builder, Model $model)
{
$builder->where('age', '>', 200);
} // 使用 addSelect 而不是 select,可以避免覆盖
}
// 需要重写给定模型的 boot 方法并使用 addGlobalScope 方法
<?php
namespace App;
use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected static function boot() {
parent::boot();
static::addGlobalScope(new AgeScope);
}
}
# 添加作用域后,如果使用 User::all() 查询则会生成如下SQL语句: select * from `users` where `age` > 200
匿名全局作用域(专门用来处理单个模型)
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class User extends Model {
protected static function boot() {
parent::boot();
static::addGlobalScope('age', function (Builder $builder) {
$builder->where('age', '>', 200);
});
}
}
移除全局作用域
# 我们还可以通过以下方式,利用 age 标识符来移除全局作用:
User::withoutGlobalScope('age')->get();
# 移除指定全局作用域
User::withoutGlobalScope(AgeScope::class)->get();
# 移除几个或全部全局作用域
User::withoutGlobalScopes([
FirstScope::class, SecondScope::class
])->get();
# 移除所有全局作用域
User::withoutGlobalScopes()->get();
本地作用域
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
public function scopePopular($query) {
return $query->where('votes', '>', 100);
}
public function scopeActive($query) {
return $query->where('active', 1);
}
}
# 在进行方法调用时不需要加上 scope 前缀
$users = App\User::popular()->active()->orderBy('created_at')->get();
$users = App\User::popular()->orWhere(function (Builder $query) {
$query->active();
})->get();
$users = App\User::popular()->orWhere->active()->get();
动态范围
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
public function scopeOfType($query, $type)
{
return $query->where('type', $type);
}
}
现在,你可以在范围调用时传递参数:
$users = App\User::ofType('admin')->get();今天关于《Laravel 模型读操作》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于mysql的内容请关注golang学习网公众号!
版本声明
本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
一文了解Docker
- 上一篇
- 一文了解Docker
- 下一篇
- Go语言SQL注入和防注入
查看更多
最新文章
-
- 数据库 · MySQL | 23小时前 |
- MySQL数值函数大全及使用技巧
- 117浏览 收藏
-
- 数据库 · MySQL | 2天前 |
- 三种登录MySQL方法详解
- 411浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- MySQL数据备份方法与工具推荐
- 420浏览 收藏
-
- 数据库 · MySQL | 3天前 |
- MySQL数据备份方法与工具推荐
- 264浏览 收藏
-
- 数据库 · MySQL | 4天前 |
- MySQL索引的作用是什么?
- 266浏览 收藏
-
- 数据库 · MySQL | 5天前 |
- MySQL排序原理与实战应用
- 392浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQLwhere条件查询技巧
- 333浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL常用数据类型有哪些?怎么选更合适?
- 234浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL常用命令大全管理员必学30条
- 448浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL高效批量插入数据方法大全
- 416浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL性能优化技巧大全
- 225浏览 收藏
-
- 数据库 · MySQL | 1星期前 |
- MySQL数据备份4种方法保障安全
- 145浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3162次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3375次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3403次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4506次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3784次使用
查看更多
相关文章
-
- golang MySQL实现对数据库表存储获取操作示例
- 2022-12-22 499浏览
-
- 搞一个自娱自乐的博客(二) 架构搭建
- 2023-02-16 244浏览
-
- B-Tree、B+Tree以及B-link Tree
- 2023-01-19 235浏览
-
- mysql面试题
- 2023-01-17 157浏览
-
- MySQL数据表简单查询
- 2023-01-10 101浏览

