• laravel 数据填充


    编写填充器

    php artisan make:seeder UserTableSeeder
    

    修改Laravel安装时自带的DatabaseSeeder类,添加一个数据库插入语句到run方法:

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

    使用模型工厂

    使用帮助函数factory来插入记录到数据库。

    创建50个用户并添加关联关系到每个用户:

    public function run(){
        factory('AppUser', 50)->create()->each(function($u) {
            $u->posts()->save(factory('AppPost')->make());
        //
    $u->posts()->saveMany(factory('AppPost', mt_rand(1,5))->make());
    }); }

    调用额外的填充器

    DatabaseSeeder类中,使用call方法执行额外的填充类

    public function run(){
        Model::unguard();
    
        $this->call(UserTableSeeder::class);
        $this->call(PostsTableSeeder::class);
        $this->call(CommentsTableSeeder::class);
    }

    运行填充器

    php artisan db:seed
    php artisan db:seed --class=UserTableSeeder

    你还可以使用migrate:refresh命令来填充数据库,该命令还可以回滚并重新运行迁移,这在需要完全重建数据库时很有用:

    php artisan migrate:refresh --seed

     运行SQL填充

        public function run()
        {
            Eloquent::unguard();
    
            $this->call('UserTableSeeder');
            $this->command->info('User table seeded!');
    
            $path = 'app/developer_docs/countries.sql';
            DB::unprepared(file_get_contents($path));
            $this->command->info('Country table seeded!');
        }
     
  • 相关阅读:
    最简单的jQuery插件
    SQL执行时间
    Resharper 8.2 注册码
    Module模式
    RestSharp使用
    使用MVC过滤器保存操作日志
    Ajax Post 类实例
    IBatis分页显示
    IBatis插入类的实例
    Topcoder SRM629 DIV2 解题报告
  • 原文地址:https://www.cnblogs.com/fenle/p/4999081.html
Copyright © 2020-2023  润新知