:::

17-1 建立訂單及品項的模型及控制器

一、同時建立模型及控制器

  1. 接著建立 Eloquent 模型,以便將一個資料表變成一個物件來操作,並且順便產生 migration 檔案(-m)以及帶有資源的控制器(-r)

    php artisan make:model Order -mr
    php artisan make:model OrderItem -mr
  2. 最後會產生 \專案\app\Order.phpOrderItem.php 模型
  3. 還會產生 \專案\app\Http\Controllers\OrderController.phpOrderItemController.php 控制器
  4. 以及\專案\database\migrations\日期_create_orders_table.php日期_create_order_items_table.php

二、修改Migration檔案

  1. 編輯日期_create_orders_table.phpup()

    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();
        });
    }
  2. 編輯日期_create_order_items_table.phpup()
    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();
        });
    }

     

  3. 最後執行資料庫遷移即可建出新的ordersorder_items兩個資料表
    php artisan migrate

 

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D43%26tbdsn%3D1451

計數器

今天: 4945494549454945
昨天: 3438343834383438
總計: 7395274739527473952747395274739527473952747395274