当前位置:网站首页>在 Laravel 中使用计算列
在 Laravel 中使用计算列
2022-06-22 10:26:00 【rorg】
MySQL 和 SQLite(从 3.31.0 版开始)支持生成的列定义。让我们看看如何在我们的数据库模式中使用计算列,以及在什么情况下我们应该将它们添加到我们的迁移中。

虚拟列和存储列
基本上有两种类型的计算列:virtual和stored。两者之间的主要区别是 virtual 每次用户运行查询时都会计算,但它不占用任何空间,但是,存储的数据需要一些空间,但每次行获取时都会更新插入或更新。简而言之:虚拟“更小”但“更慢”,存储“更大”但更快。
让我们看看一些 SQL,如何创建计算列:
drop table if exists users;
create table users (
id int auto_increment primary key,
first_name varchar(50) not null,
last_name varchar(50) not null,
salary int(10) not null,
name varchar(101) as (concat(first_name, ' ', last_name)),
insurance int(10) as (salary * 0.1) stored
);如我们所见,我们可以根据行中的其他列生成列。在某些情况下,这可能非常方便,特别是如果我们想让这些计算自动化。
迁移模式中的计算列
现在,让我们看看如何在 Laravel 迁移中添加计算列。
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('price');
$table->integer('tax')->virtualAs('price * 0.27')->nullable();
$table->integer('discount')->storedAs('price - 100')->nullable();
});请注意,Laravel 8.x 支持 SQLite 的计算列。这里的好处是,在我们的迁移中创建计算列真的很容易。这也意味着我们可以轻松地将这些附加到我们的模型中,而无需将计算属性添加到模型本身。
总结
在某些情况下,使用生成的列是一种很好的方法。如果你想使用虚拟或存储方式,这取决于你和你的情况,但它们都提供了很好的功能,并且有可能使框架本身的代码更小更清晰
边栏推荐
- 儋州清洁级动物实验室建设细节说明
- 【jenkins】shell脚本调jenkins api接口
- jg_使用easyexcel读取excel_20220619
- Who says PostgreSQL has no reliable high availability (2)
- 快速掌握 ASP.NET 身份认证框架 Identity - 登录与登出
- 软件项目管理 8.3.敏捷项目质量活动
- Byte 3: do you know what Eureka is?
- Quel est le risque de divulgation d'un certificat de signature de code?
- Cache penetration tool "Bloom filter"
- xlrd.biffh.XLRDError: Excel xlsx file; not supported 解决办法
猜你喜欢

Encryption market plummeted, Seth triggered a new round of concern

Discussion on the open source GIS solution of our company

Catch up with this big guy

Bluetooth, WiFi, ZigBee, Lora, Nb lot, call signal, network signal 4G

Signal integrity (SI) power integrity (PI) learning notes (XXIV) differential pair and differential impedance (IV)

Read the history of it development in one breath

麒麟软件携手格尔软件聚焦网络数据安全发展

Qt编写物联网管理平台36-通信协议

Tiktok practice ~ one click registration and login process of mobile phone number (verification code)

Cobalt strike from entry to imprisonment (III)
随机推荐
JG_fx_20220620
Kirin software and Geer software focus on the development of network data security
From in MySQL_ Unixtime and UNIX_ Timestamp processing database timestamp conversion - Case
Cobalt strike from starting to Imprisonment (3)
Pareto's law at work: focus on results, not outputs
After using Matplotlib for so long, I didn't know that the data could move
前 AMD 芯片架构师吐槽,取消 K12 处理器项目是因为 AMD 怂了!
牛客网——华为题库(31~40)
学会用VisualStudio开发人员工具查看对象模型
Discussion on the open source GIS solution of our company
这不会又是一个Go的BUG吧?
论文精读:Generative Adversarial Imitation Learning(生成对抗模仿学习)
Opencv人脸识别之发送QQ邮箱
TikTok 宣布将数据存储于 Oracle 服务器!
2022年深入推进IPv6部署和应用,该如何全面实现安全升级改造?
儋州清洁级动物实验室建设细节说明
使用pytorch mask-rcnn进行目标检测/分割训练
Analysis of thinkphp5.0.24 deserialization vulnerability
投资交易管理
一条TCP连接时占用内存空间多少?