:::
17-1 建立訂單及品項的模型及控制器
一、同時建立模型及控制器
-
接著建立 Eloquent 模型,以便將一個資料表變成一個物件來操作,並且順便產生 migration 檔案(-m)以及帶有資源的控制器(-r)
php artisan make:model Order -mr php artisan make:model OrderItem -mr - 最後會產生
\專案\app\Order.php及OrderItem.php模型 - 還會產生
\專案\app\Http\Controllers\OrderController.php及OrderItemController.php控制器 -
以及
\專案\database\migrations\日期_create_orders_table.php及日期_create_order_items_table.php
二、修改Migration檔案
-
編輯
日期_create_orders_table.php的up():public function up() { Schema::create('orders', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->text('address'); $table->unsignedInteger('total'); $table->boolean('closed')->default(false); $table->timestamps(); }); } - 編輯
日期_create_order_items_table.php的up():public function up() { Schema::create('order_items', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('order_id'); $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade'); $table->unsignedInteger('product_id'); $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); $table->unsignedInteger('amount'); $table->unsignedInteger('price'); $table->timestamps(); }); } - 最後執行資料庫遷移即可建出新的
orders及order_items兩個資料表php artisan migrate
17. 關於訂單
