如何将参数传递给数据库播种机中的 laravel 工厂?

How to pass parameters to laravel factory in database seeder?

是否可以将数据从播种机传递到工厂?

这是我的 PictureFactory:

class PictureFactory extends Factory{

    protected $model = Picture::class;

    public function definition($galleryId = null, $news = false){
       if (!is_null($galleryId)){
            $galley = Gallery::find($galleryId);
            $path = 'public/galleries/' . $galley->name;
            $newsId = null;
         }
        if ($news){
            $path = 'public/newsPicture';
            $newsId = News::all()->random(1);
        }

        $pictureName = Faker::word().'.jpg';
        return [
            'userId' => 1,
            'src' =>$this->faker->image($path,400,300, 2, false) ,
            'originalName' => $pictureName,
            'newsId' => $newsId
       ];
    }
}

我在数据库播种器中这样使用它:

News::factory(3)
    ->has(Comment::factory()->count(2), 'comments')
    ->create()
    ->each(function($news) { 
        $news->pictures()->save(Picture::factory(null, true)->count(3)); 
    });

$galleryId$news 不会传递给 PictureFactory。我哪里做错了?我该怎么办?请帮助我。

这就是 factory states 的用途。假设您使用的是 Laravel 的当前 (8.x) 版本,请像这样定义您的工厂:

<?php

namespace Database\Factories\App;

use App\Models\{Gallery, News, Picture};
use Illuminate\Database\Eloquent\Factories\Factory;

class PictureFactory extends Factory
{

    protected $model = Picture::class;

    public function definition()
    {
        return [
            'userId' => 1,
            'originalName' => $this->faker->word() . '.jpg',
       ];
    }

    public function withGallery($id)
    {
        $gallery = Gallery::findOrFail($id);
        $path = 'public/galleries/' . $gallery->name;

        return $this->state([
            'src' => $this->faker->image($path, 400, 300, 2, false),
            'newsId' => null,
        ]);
    }

    public function withNews()
    {
         $news = News::inRandomOrder()->first();
         $path = 'public/newsPicture';

         return $this->state([
            'src' => $this->faker->image($path, 400, 300, 2, false),
            'newsId' => $news->id,
        ]);
    }
}

现在您可以像这样创建您想要的模型:

Picture::factory()->count(3)->withNews();
// or
Picture::factory()->count(3)->withGallery($gallery_id);

我不确定,但我相信您应该能够这样做以获得您想要的结果:

Picture::factory()
    ->count(3)
    ->withNews()
    ->for(News::factory()->hasComments(2))
    ->create();