Laravel基础二之Migrations和验证

时间:2022-06-22
本文章向大家介绍Laravel基础二之Migrations和验证,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、Migration创建数据表与Seeder数据库填充数据

数据库迁移就像是数据库的版本控制,可以让你的团队轻松修改并共享应用程序的数据库结构

1.1 创建迁移

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users //添加字段

新的迁移文件会被放置在 database/migrations 目录中。每个迁移文件的名称都包含了一个时间戳,以便让 Laravel 确认迁移的顺序。 --table--create 选项可用来指定数据表的名称,或是该迁移被执行时是否将创建的新数据表。

1.2 迁移结构

迁移类通常会包含两个方法:updownup 方法可为数据库添加新的数据表、字段或索引,而 down 方法则是 up 方法的逆操作。可以在这两个方法中使用 Laravel 数据库结构生成器来创建以及修改数据表。

1.2.1 创建数据表

/**
     * 运行数据库迁移
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->comment('字段注解');
            $table->string('airline')->comment('字段注解');
            $table->timestamps();
        });
    }

    /**
     * 回滚数据库迁移
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }

1.2.2 为表添加字段

数据表、字段、索引:https://laravel-china.org/doc...

1.3 运行迁移

运行所有未完成的迁移:php artisan migrate

1.4 回滚迁移

回滚最后一次迁移,可以使用 rollback 命令:

php artisan migrate:rollback
php artisan migrate:rollback --step=5 //回滚迁移的个数
php artisan migrate:reset //回滚应用程序中的所有迁移
php artisan migrate:refresh // 命令不仅会回滚数据库的所有迁移还会接着运行 migrate 命令
php artisan migrate  //恢复

1.5 使用Seeder方式向数据库填充数据

1.5.1 编写 Seeders

php artisan make:seeder UsersTableSeeder 

1.5.2 数据库填充

 /**
     * 运行数据库填充
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }

利用模型工厂类来批量创建测试数据

php artisan make:factory PostFactory -m Post // -m 表示绑定的model

1.5.3 调用其他 Seeders

DatabaseSeeder 类中,你可以使用 call 方法来运行其他的 seed 类。

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UsersTableSeeder::class,
        PostsTableSeeder::class,
        CommentsTableSeeder::class,
    ]);
}

1.5.4 运行 Seeders

默认情况下,db:seed 命令将运行 DatabaseSeeder 类,这个类可以用来调用其它 Seed 类。不过,你也可以使用 --class 选项来指定一个特定的 seeder 类:

php artisan db:seed

php artisan db:seed --class=UsersTableSeeder

你也可以使用 migrate:refresh 命令来填充数据库,该命令会回滚并重新运行所有迁移。这个命令可以用来重建数据库:

php artisan migrate:refresh --seed

二、模型

创建模型:

php artisan make:model Models/Goods
php artisan make:model Models/Goods -m  //同时生成对应的migration文件

三、路由

批量创建路由:(资源路由)

php artisan make:controller UserController --resource
Route::resource('user', 'UserController'); //批量一次性定义`7`个路由   

根据唯一字段值来获取详情,利于SEO

Laravel 5.5 Nginx 配置: root /example.com/public; location / {

    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; }

四、验证

4.1 快速验证

4.2 表单请求验证

php artisan make:request StoreBlogPost

区别与注意

1. find 和 get

find: 通过主键返回指定的数据

$result = Student::find(1001);

get - 查询多条数据结果

DB::table("表名")->get();
DB::table("表名")->where(条件)->get();

2.模型与数据表的绑定

创建Model类型,方法里面声明两个受保护属性:$table(表名)和$primaryKey(主键)

<?php
namespace App;   
use IlluminateDatabaseEloquentModel;
class Student extends Model{
    protected $table = 'student';
    protected $primaryKey = 'id';
}    

参考教程:Coding 10编程原动力-Laravel 5.5 基础 Laravel 中文文档:Laravel 的数据库迁移 Migrations