0

Table to be created the virtual calculated column. The total column is just an example of what I expect

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->integer('price');
    $table->integer('total')->virtualAs(sum(lots.total))->defalt(0); // virtualAs Or virtualAs
});

Second table

Schema::create('lots', function (Blueprint $table) {
    $table->id();
    $table->string('description');
    $table->decimal('price');
    $table->integer('total') ;
    $table->integer('product_id'); //relationship
});

I would like to obtain the sum of the lots in the total product column

1 Answers1

0

The total should not be stored in the Db since it is redundant and can be calculated.
You should create your table and your models with the relationship for each others.
Then use the ->withCount() method to count the related lots of products.

Ex: Product::withCount('lots')->get() this will give you the number of lots associated with each product

ml59
  • 1,495
  • 1
  • 9
  • 10