温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Laravel 6.12 seeding factory don't see states

其他 - Laravel 6.12种子工厂看不到状态

发布于 2020-03-29 13:17:26

像往常一样,该项目需要种子。和往常一样,我创建一个UserFactory,进行设置,添加到DatabasesSeeder并捕获了错误。

InvalidArgumentException  : Unable to locate [models] state for [App\Models\User]

但是默认工厂(我的意思是$factory->define(User::class, function (Faker $faker))工作正常

UserTableSeeder.php

use Illuminate\Database\Seeder;
use App\Models\User;

class UserTableSeeder extends Seeder
{
    public function run()
    {
        factory(User::class, 50)->state('models')->create();
        factory(User::class, 50)->create();
    }
}

UserFactory.php

use App\Models\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;

$factory->define(User::class, function (Faker $faker) {
    //everything works fine here
});

$factory->defineAs(User::class, 'models', function (Faker $faker) {
    //exactly the same return except for a few string values
    //but 'Unable to locate [models] state for [App\Models\User]'
});

查看更多

查看更多

提问者
Tig
被浏览
14
Arnol Fokam 2020-01-31 18:14

好。我能够在环境中重现该错误。这是问题所在。您给models工厂取了名字,但好像是州一样叫了它。$ factory-> defineAs未记录)未使用状态定义工厂,而只是给工厂命名。工厂状态命名工厂(您的)是两回事。这就是为什么您不能像State Factory那样播种数据库的原因

factory(User::class, 50)->state('models')->create();

如果要使用$factory->defineAs功能,请将上面的行替换为

factory(User::class,'models', 50)->create();

要么

(推荐-因为它有据可查)如果您仍然希望能够使用->state('models')状态来播种数据库,请UserFactory.php按照以下步骤进行更改

use App\Models\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;

$factory->define(User::class, function (Faker $faker) {
    //everything works fine here
});

$factory->state(User::class, 'models', function (Faker $faker) {
    //exactly the same return except for a few string values
    //but 'Unable to locate [models] state for [App\Models\User]'
});

备注:现在,您可以使用$factory->state和不定义第二个工厂$factory->defineAs

发布
问题

分享
好友

手机
浏览

扫码手机浏览