【问题标题】:Laravel: seeding a nested set table with FakerLaravel:使用 Faker 播种嵌套的设置表
【发布时间】:2019-05-18 15:15:48
【问题描述】:

我正在使用 Kalnoy/Nestedset 并尝试使用 faker 为我的 cmets 表播种,但出现“数组到字符串转换”错误。

评论表如下所示:

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('post_id');
            $table->text('body');
            $table->timestamps();
            $table->nestedSet();
        });

评论工厂:

use Faker\Generator as Faker;

$factory->define(
    App\Models\Comment::class,
    function (Faker $faker) {
        return [
        'user_id' => function () {
            return factory('App\Models\User')->create()->id;
        },
        'post_id' => function () {
            return factory('App\Models\Post')->create()->id;
        },
        'body' => $faker->paragraph,
        ];
    }
); 

而且我真的无法弄清楚播种机必须是什么样子。这是我的尝试:

public function run(Post $post)
    {
        $node = factory('App\Models\Comment'::class, 3)->create([

            'children' => [
                [
                    factory('App\Models\Comment'::class, 2)->create([
                        'post_id' => $post->id
                    ]),

                    'children' => [
                        [ factory('App\Models\Comment'::class, 1)->create([
                        'post_id' => $post->id
                            ]), 
                        ],
                    ],
                ],
            ],
        ]);
    }

}

我也想确保孩子的帖子ID与父母的相同,但现在它返回null。

【问题讨论】:

  • 根据我的经验,“数组到字符串的转换”通常是工厂中的东西,通常是伪造者。一些facker 辅助方法采用第二个参数来指定一个数组或字符串。但我原以为paragraph 会没问题。看不到任何明显的错误。

标签: laravel nested-sets faker


【解决方案1】:

create 方法中数组的键应该是模型中存在的属性。在您的情况下,children 不是 Comment 模型上的属性。

使用Using Factories 文档中的示例,您可以创建每个评论,然后在新模型上使用children() 关系来创建它们的子模型。例如:

public function run(Post $post)
{
    $node = factory('App\Models\Comment'::class, 3) // Create the root comments.
            ->create()
            ->each(function ($comment) use ($post) { // Add children to every root.
                $comment->children()->saveMany(factory(App\Comment::class, 2)->make([
                    'post_id' => $post->id
                ]))
                ->each(function ($comment)  use ($post) { // Add children to every child of every root.
                     $comment->children()->saveMany(factory(App\Comment::class, 2)->make([
                        'post_id' => $post->id
                    ]));
                });
            });

【讨论】:

  • 成功了,谢谢!我将此代码包装在 "factory('App\Models\Post'::class, 5)->create()->each(function($post){ " 以正确获取帖子 ID 并改为运行 Post seeder。
猜你喜欢
  • 2018-05-26
  • 1970-01-01
  • 2018-09-03
  • 2023-03-03
  • 2017-08-29
  • 2015-06-02
  • 2019-01-31
  • 2021-04-01
  • 1970-01-01
相关资源
最近更新 更多