【问题标题】:Laravel Database Seeder ClassLaravel 数据库播种器类
【发布时间】:2018-05-20 00:43:01
【问题描述】:

这是我的 DatabaseSeeder 类代码

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {


        $this->call(
            AdminSeeder::class,
            CategorySeeder::class,
            UsersSeeder::class,);
    }
}

我的 php Artisan 命令是:php artisan db:seed 我想用一个逗号迁移所有 Seeder 类。但我做不到。请帮助我。

【问题讨论】:

    标签: php database laravel-5.4


    【解决方案1】:

    call() 方法需要一个数组,而不是参数列表,因此正确的调用是

        $this->call([
            AdminSeeder::class,
            CategorySeeder::class,
            UsersSeeder::class,
        ]);
    

    这里的关键是从 Laravel 框架 5.5 版本开始接受数组。以前,包括您现在使用的 v5.4,只允许单个类名(字符串)作为参数。所以如果不能升级到5.5,就需要单独调用所有的类,即:

        $cls = [
            AdminSeeder::class,
            CategorySeeder::class,
            UsersSeeder::class,
        ];
        foreach ($cls as $c) {
           $this->call($c);
        }
    

    Docs for v5.4docs for v5.5

    【讨论】:

    • 但是这个 $this->call([ AdminSeeder::class, CategorySeeder::class, UsersSeeder::class, ]);过程没有奏效。数组到字符串的转换错误。我该如何解决?
    【解决方案2】:

    您还可以分别调用每个播种机。

    $this->call('AdminSeeder');
    $this->call('CategorySeeder');
    $this->call('UsersSeeder');
    

    为downvoter 编辑call 函数可以接受数组或字符串。

    /**
     * Seed the given connection from the given path.
     *
     * @param  array|string  $class
     * @param  bool  $silent
     * @return $this
     */
    public function call($class, $silent = false)
    {
        $classes = Arr::wrap($class);
        foreach ($classes as $class) {
            if ($silent === false && isset($this->command)) {
                $this->command->getOutput()->writeln("<info>Seeding:</info> $class");
            }
            $this->resolve($class)->__invoke();
        }
        return $this;
    }
    

    【讨论】:

    • 你好,反对者,你能在这里说明你的理由吗?你在投反对票之前尝试过吗?这适用于 laravel4.1 ~ laravel5.5。
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2020-04-04
    • 1970-01-01
    • 2018-12-11
    • 2016-02-10
    • 2017-11-27
    • 2021-04-01
    相关资源
    最近更新 更多