How to create a migrate and add a calculated column to an existing table in the database?

Asked

Viewed 205 times

0

I have the ratings table that has the columns Nota1, nota2, nota3, nota4 created in the database and wanted to create a media column that already computes the media automatically, how to create that column compute using the migrate of the Laravel ?

public function up()
    {
        Schema::create('avaliacoes', function(Blueprint $table)
        {
            $table->increments('id');           
            $table->integer('nota1')->default(0);
            $table->integer('nota2')->default(0);
            $table->integer('nota3')->default(0);
            $table->integer('nota4')->default(0);
            //criar columa media aqui = (nota1+nota2+nota3+nota4) / 4

        });
    }



nota1 | nota2 | nota3 | nota4 | // criar coluna media
 2    |    3  |     4 |     5 | // Media aqui
  • In the table you place the necessary fields for storage, that is, if you can create a media field and by code (because I don’t even need this field) or a trigger to calculate this. I would do it for the code that is just creating one more configuration in your eloquent model and the same already does it for you allowing you to have a calculated field in your model. What do you think?

  • This modeling is a little strange, but within the structure you have there you will create the field, and within your controller (if you do not use dependency injection) you calculate the average of the grades.

  • I was able to solve it with the tip you guys gave.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.