如何在 Laravel 数据库填充器中向工厂传递参数?

3
可以将种子数据传递给工厂吗?
这是我的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,我错在哪里了?我应该怎么办?请帮帮我。
1个回答

12

这就是工厂状态的应用场景。假设您正在使用当前(8.x)版本的Laravel,请像这样定义您的工厂:

<?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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接