代码之家  ›  专栏  ›  技术社区  ›  Carlos Salazar

将父id传递给关系工厂?

  •  0
  • Carlos Salazar  · 技术社区  · 6 年前

    我有一家工厂 posts 还有一个工厂 posts_images ,一个帖子可以有很多图片,我确实为这样的帖子创建了一个播种器。

    $posts = factory(App\Models\Post::class, 100)->create()
    ->each(function($post) {
        $post->images()->saveMany(factory(App\Models\PostsImage::class, 3)->make());
    });
    

    我想创造 100 posts 每个职位都有 3 images ,这类工作的问题是图像创建时

    我希望从一个基字符串创建图像并保存在某个目录中,但是我需要 id post 所以我可以创建创建它的文件夹。

    $factory->define(App\Models\PostsImage::class, function (Faker $faker) {
        //this does not get me the id
        $id = factory(\App\Models\Post::class)->make()->id;
        $name      = time();
        $b64_image = \Config::get('constants.seed_image');
        $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $b64_image));
        if(!file_exists(public_path('images/eventos/'.$id.'/'))) {
            mkdir(public_path('images/noticias/'.$id.'/'));
        }
        file_put_contents(public_path('images/noticias/'.$id.'/'.$name.'.jpg'), $data);
        return [
            //
            'image'   => $name,
            'order'   => $id + 1
        ];
    });
    

    唯一不起作用的是

    $id = factory(\App\Models\Post::class)->make()->id;
    

    我试过用 create 而不是 make ,但这会在 邮递 桌子,我不想要。

    有没有办法通过 邮递 身份证件 去图像工厂?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Elisha Senoo    6 年前

    最好的选择是在 posts 播种机,既然你有权 $post 对象时 Post 是创建的。试试这样的:

    $posts = factory(App\Models\Post::class, 100)->create()
    ->each(function($post) {
        //id is available on the $post object created
        $id = $post->id;
        $name      = time();
        $b64_image = \Config::get('constants.seed_image');
        $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $b64_image));
        if(!file_exists(public_path('images/eventos/'.$id.'/'))) {
            mkdir(public_path('images/noticias/'.$id.'/'));
        }
        file_put_contents(public_path('images/noticias/'.$id.'/'.$name.'.jpg'), $data);
        $post->images()->saveMany(factory(App\Models\PostsImage::class, 3)->make());
    });