php框架laravel學習 二 (數據庫建立遷移與建模)

一、數據庫遷移

使用wampServer中的phpmyadmin 新建數據庫blog,使用默認mysql賬號root 密碼爲空。
Laravel5 把數據庫配置的地方改到了 blog/.env,打開這個文件,修改爲wampServer mysql數據庫信息:

DB_HOST=localhost
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=

在cmd下運行

php artisan migrate

執行成功將會顯示

D:\wamp\www\test\blog>php artisan migrate
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table

如果你運行命令報錯,請檢查數據庫連接設置。
至此,數據庫遷移已完成,可以在phpMyAdmin中查看blog數據庫下多了三個表。

二、模型 Models

cmd下輸入

php artisan make:model Article
php artisan make:model Page

Laravel5 已經把 Generator 集成進了 Artisan,上面2條命令將會在blog/app/目錄下創建兩個文件,Article.phpPage.php,這是兩個 Model 類,他們都繼承了 Laravel Eloquent 提供的 Model 類 Illuminate\Database\Eloquent\Model,且都在 \App 命名空間下。

接下來進行 Article 和 Page 類對應的 articles 表和 pages表的數據庫遷移,進入 learnlaravel5/database/migrations 文件夾。

在 ***_create_articles_table.php 中修改:

Schema::create('articles', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('title');
    $table->string('slug')->nullable();
    $table->text('body')->nullable();
    $table->string('image')->nullable();
    $table->integer('user_id');
    $table->timestamps();
});

在 ***_create_pages_table.php 中修改:

Schema::create('pages', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('title');
    $table->string('slug')->nullable();
    $table->text('body')->nullable();
    $table->integer('user_id');
    $table->timestamps();
});

然後執行命令:

php artisan migrate

成功之後,在blog數據庫中新增了articles表和pages表

三、數據庫填充Seeder
在blog/database/seeds/目錄下新建PageTableSeeder.php文件,內容如下:

<?php

use Illuminate\Database\Seeder;
use App\Page;

class PageTableSeeder extends Seeder {
  public function run()
  {
    DB::table('pages')->delete();

    for ($i=0; $i < 10; $i++) {
      Page::create([
        'title'   => 'Title '.$i,
        'slug'    => 'first-page',
        'body'    => 'Body '.$i,
        'user_id' => 1,
      ]);
    }
  }
}

然後修改同一級目錄下的 DatabaseSeeder.php中:

// $this->call('UserTableSeeder');

這一句爲

$this->call('PageTableSeeder');

然後運行命令進行數據填充:

composer dump-autoload

php artisan db:seed

成功之後 發現pages表中已經多了10行數據。

發佈了53 篇原創文章 · 獲贊 9 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章