簡體   English   中英

如何在 Laravel Migration 中從另一個表創建虛擬計算列?

[英]How to Create a virtual calculated column in Laravel Migration from another table?

要創建虛擬計算列的表。 總列只是我期望的一個例子

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()這將為您提供與每個產品相關的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM