Laravel 4 初级教程之安装及入门(2)
php artisan migrate --package=cartalyst/sentry
执行完成后,你的数据库里就有了5张表,这是sentry自己建立的。sentry在Laravel4下的配置详情见 https://cartalyst.com/manual/sentry#laravel-4,我大致说一下:
在 ./app/config/app.php 中 相应的位置 分别增加以下两行:
'Cartalyst\Sentry\SentryServiceProvider',
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',
权限系统的数据库配置到此为止。
我们的简单blog系统将会有两种元素,Article和Page,下面我们将创建articles和pages数据表,命令行运行:
php artisan migrate:make create_articles_table --create=articles
php artisan migrate:make create_pages_table --create=pages
这时候,去到 ./app/database/migrations,将会看到多出了两个文件,这就是数据库迁移文件,过一会我们将操作artisan将这两个文件描述的两张表变成数据库中真实的两张表,放心,一切都是自动的。
下面,在***_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
这时候数据库中的articles表和pages表就建立完成了。
4. 模型 Models
接下来我们将接触Laravel最为强大的部分,Eloquent ORM,真正提高生产力的地方,借用库克的话说一句,鹅妹子英!
我们在命令行运行下列语句以创建两个model:
php artisan generate:model article
php artisan generate:model page
这时候,在 ./app/models/ 下就出现了两个model文件。这两个类继承了Laravel提供的核心类 \Eloquent。
5. 数据库填充
分别运行下列命令:
php artisan generate:seed page
php artisan generate:seed article
这时,在 ./app/database/seeds/ 下就出现了两个新的文件,这就是我们的数据库填充文件。Laravel提供自动数据库填充,十分方便。
generator默认使用Faker\Factory作为随机数据生成器,所以我们需要安装这个composer包,地址是 https://packagist.org/packages/fzaninotto/faker ,跟generator一起安装在 require-dev 中即可。具体安装请自行完成,可以参考Sentry和Generator,这是第一次练习。
接下来,分别更改这两个文件: