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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.