zoukankan      html  css  js  c++  java
  • 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!');
        }
     
  • 相关阅读:
    在xcode5中修改整个项目名
    如何调试堆损坏
    My Life with Isaac Stern by Aaron Rosand
    Seagate 硬盘产地查询
    服务器返回 HTTP 500
    Exception code: 0xE0434352
    When curl sends 100-continue
    Milestone 不能卸载,修复 Counter 即可
    GE 遇到的 UAC 导致不能自动启动的问题
    关于 UAC,Mark Russinovich on the Future of Security
  • 原文地址:https://www.cnblogs.com/fenle/p/4999081.html
Copyright © 2011-2022 走看看