gpt4 book ai didi

php - 在 Laravel eloquent 数据库播种机/工厂中播种关系数据 - 类型错误 - Arg 1 应该是 Eloquent\Model - 给定集合

转载 作者:行者123 更新时间:2023-12-04 00:05:38 32 4
gpt4 key购买 nike

我正在尝试在 Laravel 5.5 应用程序中为一个包含关系数据的表添加种子。

我有这两个表/模型:

  • 用户
  • 问题

app\User.php 模型文件上;我有以下 hasMany 关系:

public function questions()
{
return $this->hasMany(Question::class);
}

这是我的database/factories/QuestionFactory.php

<?php

use Faker\Generator as Faker;

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

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

还有我的database/factories/UserFactory.php

<?php

use Faker\Generator as Faker;

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

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

鉴于上述情况;我正在尝试在我的虚拟数据播种器中使用它,如下所示:

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

The goal was to create 10 dummy users, and for each users to have 3 questions each.

当我使用上述设置为数据库播种时;我收到以下错误:

[Symfony\Component\Debug\Exception\FatalThrowableError] Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in C:\xampp\htdocs\myapp.local\database\seeds\DummyDataSeeder.php on line 18

最佳答案

试试这样:

factory(App\User::class, 10)->create()->each(function ($u) {
$u->questions()->saveMany(factory(App\Question::class, 3)->make());
});

关于php - 在 Laravel eloquent 数据库播种机/工厂中播种关系数据 - 类型错误 - Arg 1 应该是 Eloquent\Model - 给定集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46886532/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com