如何在数据库播种机中将参数传递给拉拉维尔工厂?



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

这是我的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.我哪里做错了?我该怎么办?请帮助我。

这就是工厂状态的用途。假设您使用的是当前 (8.x) 版本的 Laravel,请按如下方式定义您的工厂:

<?php
namespace DatabaseFactoriesApp;
use AppModels{Gallery, News, Picture};
use IlluminateDatabaseEloquentFactoriesFactory;
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();

最新更新