[英]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
。 我哪里做錯了? 我該怎么辦? 請幫我。
這就是工廠狀態的目的。 假設您使用的是當前 (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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.