【发布时间】:2019-04-01 06:19:48
【问题描述】:
我有一个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,这种工作,问题是创建图像时
我希望从 base_64 字符串创建图像并将其保存在某个目录中,但我需要 post 的 id 以便我可以创建将要创建它的文件夹。
$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,但这会在 post 表中创建更多行,我不希望这样。
有没有办法将post id 传递给图像工厂?
【问题讨论】:
-
如果你在做
make,你永远不会有id,因为你没有保存它,只是创建了那个类的实例 -
完全是@matiaslauriti,所以 id 仅在创建时可用。
-
@ElishaSenoo 这个
factory(\App\Models\Post::class)->make()->id将返回 null -
$post->id,如下面我的回答,有 id
标签: php laravel eloquent factory