常常会用到 artisan 的一些命令,往往要去查文档,翻弄半天,不方便,这里归纳在这里
一、控制器
- 5.1
--plain用于创建一个空的控制器而不是标准的 RESTful 风格控制器。 - 5.2
--plain无效,默认即是空的控制器,要自带生成各类方法框架需要添加参数:--resource
php artisan make:controller BlogController --resource
则生成的方法和5.1前,没有添加任何参数生成的控制器一样。
二、模型和数据库迁移
1、创建模型的同时创建表的迁移
php artisan make:model --migration Post
或:
php artisan make:model --m Post
上述命令会做两件事情:
- 在 app 目录下创建模型类 App\Post;
- 创建用于创建 posts 表的迁移,该迁移文件位于 database/migrations 目录下。
生成的迁移文件的关键位置是:
Schema::create('posts', function (Blueprint $table) {
注意,是Schema::create。
2、创建表的迁移
php artisan make:migration create_users_table --create=users
--create=users:该迁移是否要创建一个新的数据表users
3、修改表字段的迁移
在 Laravel 5.1 中如果需要修改数据表的列,则需要安装 Doctrine 依赖包,我们使用 Composer 安装该依赖包:
composer require "doctrine/dbal"
接下来使用 Artisan 命令创建新的迁移文件:
php artisan make:migration --table=posts restructure_posts_table
restructure是关键字,--table=posts指定了要操作的表
生成文件的关键位置为:
Schema::table('posts', function (Blueprint $table) {
// ......
$table->renameColumn('content', 'content_raw');
// ......
change():修改已存在的列为新的类型,或者修改列的属性。
$table->string('name', 50)->change();即就是修改 name 列的尺寸为50。
$table->string('name', 50)->nullable()->change();即就是修改 name 列为可空。
列修改器列表:
| 修改器 | 描述 |
|---|---|
->first() |
将该列置为表中第一个列 (仅适用于MySQL) |
->after('column') |
将该列置于另一个列之后 (仅适用于MySQL) |
->nullable() |
允许该列的值为NULL |
->default($value) |
指定列的默认值 |
->unsigned() |
设置 integer 列为 UNSIGNED |
更多信息可参考 laravel学院的文档
4、添加新字段到已存在的表
php artisan make:migration alter_posts_deleted_at --table=posts
alter是关键字,--table=posts指定要操作的表
生成文件的关键位置为:
Schema::table('posts', function (Blueprint $table) {
5、创建迁移文件:关系表
php artisan make:migration create_user_accounts_table --create=user_accounts
创建表:user_accounts
关键行:
Schema::create('user_accounts', function (Blueprint $table) {
6、运行迁移
php artisan migrate
可以接的参数:
--force:在生产环境中强制运行迁移