尝试创建API,其中用户创建一个包含食物标题和烹饪时间的帖子,并且他们可以在两个表中发布最多2张图片,在两个不同的数据库中发布post_images。 存储功能运行良好,但是我对更新功能一无所知。我可以通过邮递员更新所有帖子数据,但是图像没有更新
public function store(Request $request)
{
$post = new Post;
$post->setConnection('mysql1');
$user = User::where('id', $request->id)->first();
if ($user) {
$post = Auth::user()->posts()->create([
'user_id' => Auth::id(),
'post_id' => rand(),
'title' => $request->title,
'cooked_time' => strtotime($request->cooked_time),
]);
$images = new PostImage;
$destination_path = public_path('/images');
if ($request->hasFile('image1')) {
$image1 = $request->file('image1');
$image_size1 = $image1->getClientSize();
$image_ext1 = $image1->getClientOriginalExtension();
$new_image_name1 = rand(123456, 99999999) . "." . $image_ext1;
$image1->move($destination_path, $new_image_name1);
$images->image_name1 = $new_image_name1;
}
if ($request->hasFile('image2')) {
$image2 = $request->file('image2');
$image_size2 = $image2->getClientSize();
$image_ext2 = $image2->getClientOriginalExtension();
$new_image_name2 = rand(123456, 99999999) . "." . $image_ext2;
$image2->move($destination_path, $new_image_name2);
$images->image_name2 = $new_image_name2;
}
$images->post_id = $post->post_id;
$images->save();
$post = json_decode($post);
$post->image1 = $images->image_name1;
$post->image2 = $images->image_name2;
if ($post && $images) {
return $this->successResponse($post);
} else {
return $this->errorResponse("Post Failed", 200);
}
}
}
我的更新代码有点类似
public function update(Request $request, $post_id)
{
$posts = Post::findorFail($post_id);
if (Auth::user()->id !== $posts->user_id) {
return response()->json(['status' => 'error', 'message' => 'unauthorized'], 401);
}
$post1 = $request->all();
$posts->fill($post1)->save();
$image = PostImage::where('post_id', $posts->post_id)->get()->first();
$images = PostImage::findorFail($image->id);
if ($request->hasFile('image1')) {
$image1 = $request->file('image1');
$image_size1 = $image1->getClientSize();
$image_ext1 = $image1->getClientOriginalExtension();
$new_image_name1 = $post_image['image_name1'] . "." . $image_ext1;
$image1->move($destination_path, $new_image_name1);
$images->image_name1 = $new_image_name1;
}
if ($request->hasFile('image2')) {
$image2 = $request->file('image2');
$image_size2 = $image2->getClientSize();
$image_ext2 = $image2->getClientOriginalExtension();
$new_image_name2 = $post_image['image_name2'] . "." . $image_ext2;
$image2->move($destination_path, $new_image_name2);
$images->image_name2 = $new_image_name2;
}
$images->post_id = $post->post_id;
$images->save();
return response()->json(['status' => 'success', 'updated_post' => $posts, 'images' => $images], 200);
}
如果要通过邮递员传递图像参数,我想实现更新请求以同时更新图像和帖子。