php - 在 Laravel 中实现多图像上传系统时遇到问题

标签 php mysql file-upload laravel laravel-4

在我的网络应用程序中,人们可以创建帖子。除了这些帖子之外,他们还可能上传多张图片。为此,我有一个帖子表和一个图像表。帖子有很多图片,一张图片属于一篇帖子。因此,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/

相关文章:

php - 在批处理文件中设置路径

php - 使用友好的 url 更改 .htaccess 时无法获取变量

php - 一次从 mySQL 数据库中删除多个值

Mysql JOIN 获取指定列数据语法错误

mysql - 从 MySql 导出转储文件

php - 从 Android 应用程序上传多个图像到服务器

javascript - Meteor:无法使用 CollectionFS 将图像上传到 S3

php strlen() 在不同环境下对同一个字符串获取不同的值

php - 使用Json格式减少MySQL中的JOIN

iphone - 如何找到上传的剩余时间