当前位置:网站首页>Using computed columns in laravel

Using computed columns in laravel

2022-06-22 10:33:00 rorg

MySQL and SQLite( from 3.31.0 version ) Support generated column definitions . Let's see how to use computed columns in our database schema , And when we should add them to our migration .

 

Virtual and storage columns

There are basically two types of computed columns :virtual and stored. The main difference between the two is virtual Each time a user runs a query, it calculates , But it doesn't take up any space , however , The stored data needs some space , But the insert or update is updated every time the row is retrieved . In short : fictitious “ smaller ” but “ More slowly ”, Storage “ Bigger ” But faster .

Let's take a look at some SQL, How to create a calculated column :

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
);

As we can see , We can generate columns from other columns in the row . In some cases , It can be very convenient , Especially if we want to automate these calculations .

Calculated columns in the migration mode

Now? , Let's see how Laravel Add calculated column in migration .

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();
});
Please note that ,Laravel 8.x Support SQLite The computed column of .

The advantage here is , It's really easy to create computed columns in our migration . This also means that we can easily add these to our model , Instead of adding calculated attributes to the model itself .

Besides , The important thing is that we can index the computed columns . therefore , It can also improve performance .

summary

In some cases , Using the generated columns is a good way . If you want to use virtual or storage , It depends on you and your situation , But they all provide good functionality , And it is possible to make the code of the framework itself smaller and clearer

原网站

版权声明
本文为[rorg]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221026059694.html