鉴于我有以下表格:
my pivot table with two fields: question_id & tag_id
我的 App \ Question 模型具有以下关系:
class Question extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->hasMany(Tag::class);
}
}
我创建了以下工厂:
数据库/工厂/ 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')
];
});
数据库/工厂/ 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)
];
});
数据库/工厂/ 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()期望参数1为字符串, 数组给出
模型工厂不可能做到这一点吗?我需要使用不同的方法吗?
答案 0 :(得分:0)
我认为您需要将belongsToMany用于数据透视表
在你的问题模型中
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。
答案 1 :(得分:0)
来自fzaninotto/Faker自述文件:
words($nb = 3, $asText = false) // array('porro', 'sed', 'magni')
。
将返回数组
Laravel str_slug()
str_slug函数生成一个URL友好的" slug"从给定的字符串:
$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))),