在我的网络应用程序中,人们可以创建帖子。除了这些帖子之外,他们还可能上传多张图片。为此,我有一个帖子表和一个图像表。帖子有很多图片,一张图片属于一篇帖子。因此,images 表具有 image_path 列和 post_id 列。我的麻烦是获取 post_id。因为在帖子上传之前我无法获取帖子ID,所以我无法设置图像属于哪个帖子。无论如何,这里有一些代码:
public function create(){
$post = new Post;
$post->title=Input::get('title');
$post->body=Input::get('body');
$post->category=Input::get('category');
$post->save();
$images = Input::file('images');
foreach($images as $image) {
$destinationPath = 'public/uploads/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$id=Auth::id();
$file = new Image();
$file->image_path = 'uploads/' . $image->getClientOriginalName();
$file->description = '';
$file->post_id=Input::get('post_id');
$file->save();
}
解决此问题的最佳方法是什么?
最佳答案
使用 $post->save()
保存 Post
后,您可以使用以下方法获取 id:
// ...
$post->save();
/...
$file->post_id = $post->id;
您可以尝试这样做:
// ...
$post->save();
$destinationPath = 'uploads/';
$images = Input::file('images');
foreach($images as $image) {
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$file = new Image();
$file->image_path = 'uploads/' . $image->getClientOriginalName();
$file->description = '';
$post->images->save($file);
}
关于php - 在 Laravel 中实现多图像上传系统时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24313548/