问题描述
要创建的表为虚拟计算列。 总栏仅是我期望的示例
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
});
第二张表
Schema::create('lots',function (Blueprint $table) {
$table->id();
$table->string('description');
$table->decimal('price');
$table->integer('total') ;
$table->integer('product_id'); //relationship
});
我想在“总产品”列中获取批次的总和
解决方法
总计不应该存储在Db中,因为它是多余的并且可以计算。
您应该创建具有彼此关系的表和模型。
然后使用->withCount()
方法计算产品的相关批次。
例如:Product::withCount('lots')->get()
,这将为您提供与每个产品