Laravel数据库填充器类

3

这是我的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类,但我做不到,请帮帮我。
2个回答

2

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);
    }

5.4版本文档5.5版本文档中有关于调用额外种子数据的信息。


但是这个 $this->call([ AdminSeeder::class, CategorySeeder::class, UsersSeeder::class, ]); 过程没有执行成功,报了“数组转换为字符串”的错误。我该怎么解决? - Ruhul

0

你也可以单独调用每个种子。

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

针对给我点踩的人进行编辑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都可以很好地工作。 - LF00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接