Alex Dai Playground

[Laravel] cli

| Comments

建立資料表

  • 產生 book model
    php artisan make:model Book
    
  • 產生 books table

    php artisan make:migration create_books_table
    
  • 設定 books schema

    2016_10_05_085026_create_books_table.php
    class CreateBooksTable extends Migration
    {
    public function up()
    {
    Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('author');
    $table->integer('price', 0);
    $table->timestamps();
    });
    }
    ...
    }


    • Schema 寫入資料庫
      php artisan migrate
      

    資料表更新

    • 產生更新遷移檔,指定 books table
      php artisan make:migration add_userid_to_books_table --table="books"
      
    • 撰寫更新程式碼 (新增外來鍵失敗,遷移順序問題?)

      2016_10_17_030053_add_userid_to_books_table.php
      class AddUseridToBooksTable extends Migration
      {
        public function up()
        {
            Schema::table('books', function (Blueprint $table) {
                // 新增外來鍵欄位 對應使用者 id
                $table->integer('user_id')->unsigned();
      
                $table->foreign('user_id')
                    ->references('id')
                    ->on('users')
                    ->onDlete('cascade');
                });
        }
      
        public function down()
        {
            Schema::table('books', function (Blueprint $table) {
                  $table->dropColumn('user_id');
            });
        }
      }
      
    • 更新 Schema

      php artisan migrate
      
    • https://laravel.com/docs/5.1/migrations#creating-tables

    • http://laravel5-book.kejyun.com/database/migration/database-migration-README.html

Comments

comments powered by Disqus