Laravel在到达路由时创建数据库输入


Laravel create database entery when hitting a route?

我还在自学拉拉维尔。我正在 laravel 制作订单,我有一张装满产品的桌子,我想让它在下新订单并添加产品时制作。当我单击新订单时,它会制作自己的订单,它会创建一个新的订单号并将其保存到数据库中?

最好的方法是制作订单表

Schema::create('westcoOrders', function (Blueprint $table){
        $table->increments('id');
        $table->string('orderNumber');
        $table->json('content');
        $table->tinyInteger('sent')->default(0);
        $table->tinyInteger('delivered')->default(0);
        $table->timestamps();
    } );
或者最好有一个表多个表,

所以我有一个像上面这样的表,没有 json 条目,然后有一个这样的 westcoOrderItems 表?

Schema::create('westcoOrderItems', function (Blueprint $table){
        $table->string('orderNumber');
        $table->string('quantity');
        $table->string('productName');
        $table->string('productCode');
        $table->string('price');
        $table->timestamps();
    } );
}

因此,我将订单号链接到另一个表。还是说,这还有很长的路要走?如果我这样做,我将不得不在遇到新的订单路线时找到一种方法来制作订单号?

我觉得我这样做是错误的/漫长的?

在我看来,像下面这样的东西会更好:

// For orders
Schema::create('orders', function (Blueprint $table){
    $table->increments('id');
    $table->tinyInteger('is_delivered')->default(0);
    $table->tinyInteger('is_paid')->default(0);
    $table->timestamps();
});
// For ordered_items (one order may contain many products/ordered_items)
Schema::create('ordered_items', function (Blueprint $table){
    $table->increments('id')->unsigned();
    $table->integer('order_id')->unsigned(); // fk for order.id
    $table->string('quantity')->unsigned();
    $table->string('productName');
    $table->string('productCode');
    $table->decimal('price', 10, 2);
});

然后是模型,例如:

namespace App;
use Illuminate'Database'Eloquent'Model;
class Order extends Model {
    public function items()
    {
        return $this->hasMany('Item::class');
    }
}

ordered_items Item类:

namespace App;
use Illuminate'Database'Eloquent'Model;
class Item extends Model {
    protected $table = 'ordered_items';
    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}

希望你明白了。这是最简单的一个。