$post = $request->user()->posts()->create($request->all());
$imageData = json_decode($request['imageData']) ?: null;
$image = $this->imageHandler->make($request['image'], $imageData);;
$post->image()->save($image);
Log::debug($post->image->thumbnail);
当我这样做时,Log
命令(以及日志本身(中的$post->image->thumbnail
为空。我不明白为什么会发生这种情况 - 如果我提交随后显示的视图并使用$post->image->thumbnail
就可以了,如果我进入artisan tinker
我可以做$post->image
就可以了。出于某种原因,在发布帖子后的控制器中,它说它不存在。此外,当它调用 Algolia 助手来保存/索引帖子时,它也不包括image
。
编辑:我在修补中尝试过这个,但也遇到了问题:
$post = factory(AppUser::class)->create()->posts()->save(factory(AppPost::class)->make());
返回新用户并发布
$image = factory(AppImage::class)->create();
返回新图像
$post->image()->save($image);
这返回假
$image现在是:
AppImage {#761
filename: "placeholder2.png",
updated_at: "2015-12-09 01:31:31",
created_at: "2015-12-09 01:31:22",
id: 91,
post_id: 104,
post: null,
}
$post->image
为空。 $image->post
为空。但$image正确地post_id。
如果我关闭修补并重新打开它并$image = AppImage::find(91)
,现在$image->post
正确返回帖子。我不明白这里发生了什么。
这行代码:
$imageData = json_decode($request['imageData']) ?: null;
据我所知,无论结果如何,都将$imageData设置为"null"。如果这是完整的代码,那么您的问题很可能源于$imageData始终为 null。请尝试:
$imageData = $request['imageData'] ? json_decode($request['imageData']) : null;
图片保存到帖子后,关系仍然没有加载。但是,当再次查询它时,下次将加载关系。
因此,在将$image保存到$post后,我所要添加的只是$post->load('image');
,然后可以访问$post->image
。