php框架laravel学习 二 (数据库建立迁移与建模)

来源:互联网 发布:福建广电网络人工电话 编辑:程序博客网 时间:2024/04/26 09:11

一、数据库迁移

使用wampServer中的phpmyadmin 新建数据库blog,使用默认mysql账号root 密码为空。
Laravel5 把数据库配置的地方改到了 blog/.env,打开这个文件,修改为wampServer mysql数据库信息:

DB_HOST=localhostDB_DATABASE=blogDB_USERNAME=rootDB_PASSWORD=

在cmd下运行

php artisan migrate

执行成功将会显示

D:\wamp\www\test\blog>php artisan migrateMigration table created successfully.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_table

如果你运行命令报错,请检查数据库连接设置。
至此,数据库迁移已完成,可以在phpMyAdmin中查看blog数据库下多了三个表。

二、模型 Models

cmd下输入

php artisan make:model Articlephp 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文件,内容如下:

<?phpuse 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-autoloadphp artisan db:seed

成功之后 发现pages表中已经多了10行数据。

0 0