使用 Laravel 5.5 模型工厂播种枢轴 table - mb_strtolower() 期望参数 1 为字符串,数组给定

Seeding pivot table with Laravel 5.5 model factory - mb_strtolower() expects parameter 1 to be string, array given

鉴于我有下表:

和我的App\Question模型有以下关系:

class Question extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function tags()
    {
        return $this->hasMany(Tag::class);
    }
}

我创建了以下工厂:

database/factories/UserFactory.php

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('123456')
    ];
});

database/factories/QuestionFactory.php

$factory->define(App\Question::class, function (Faker $faker) {
    static $user_id;

    return [
        'user_id' => $user_id,
        'subject' => $faker->sentence(15),
        'body' => $faker->paragraph(10)
    ];
});

database/factories/TagFactory.php

$factory->define(App\Tag::class, function (Faker $faker) {
    return [
        'name' => str_slug($faker->words(mt_rand(1, 2))),
        'description' => $faker->sentence()
    ];
});

我试着像这样在我的虚拟数据播种机中一起使用它们:

class DummyDataSeeder extends Seeder
{
    public function run()
    {
        // Seed dummy users
        factory(App\User::class, 10)->create()->each(function($user)
        {
            // With dummy questions
            $user->questions()->saveMany(factory(App\Question::class, 10)->make()->each(function($question)
            {
                // With dummy tags
                $question->tags()->sync(factory(App\Tag::class, 3)->make());
            }));
        });
    }
}

当我 运行 播种器时,出现以下错误:

[ErrorException] mb_strtolower() expects parameter 1 to be string, array given

这在模型工厂是做不到的吗?我需要使用不同的方法吗?

我认为你需要使用 belongsToMany 作为你的数据透视表 Table

在你的问题模型中

public function tags()
 {
  return $this->belongsToMany(Tag::class,'question_tag','tag_id','question_id');
 }

与您的标签模型相同

public function questions()
{
 return $this->belongsToMany(Question::class,'question_tag','question_id','tag_id');
}

此外,您需要更改

 $question->tags()->sync(factory(App\Tag::class, 3)->make());

$tags = factory(App\Tag::class, 3)->make();
$tagIds = Tag::select('id')->get()->toArray();
 $question->tags()->sync($tagIds);

这意味着您需要在 Sync 参数中传递 ID。

来自 fzaninotto/Faker 自述文件:

words($nb = 3, $asText = false) // array('porro', 'sed', 'magni').

将return数组

Laravel str_slug()

The str_slug function generates a URL friendly "slug" from the given string: $slug = str_slug('Laravel 5 Framework', '-');

str_slug 需要字符串

在您的 database/factories/TagFactory.php 中,您需要修复以下行:

'name' => str_slug($faker->words(mt_rand(1, 2))),

'name' => str_slug(implode(' ', $faker->words(mt_rand(1, 2)))),

或者也许

'name' => str_slug($faker->sentence(mt_rand(1, 2))),