【问题标题】:Polymorphic Relation - Can not store all files at database?多态关系 - 无法将所有文件存储在数据库中?
【发布时间】:2018-09-15 11:11:09
【问题描述】:

我正在尝试将帖子图像存储在数据库中,并且我正在使用 dropzonejs。我可以将图像存储在存储中,我的意思是图像成功移动存储文件夹。但是当我在数据库中存储时,发生了奇怪的问题.. Laravel 只在数据库中插入了一些图像?

例如,我上传了 10 张图片,所有文件都移动了存储文件夹,但在数据库中只显示了 3 条记录?有时两个或四个..

我该如何解决这个问题?

放置区配置

Dropzone.options.mDropzoneTwo = {
        paramName: "images",
        maxFiles: 10,
        maxFilesize: 2, // MB
        url: '../../media/store',
        method: 'POST',
        headers: {
            "X-CSRF-TOKEN": token,
        },
        uploadMultiple: true,

        accept: function (file, done) {
            done();
        },

        init: function() {
            this.on("sending", function(file, xhr, formData){
                formData.append("post_type", post.dataset.type);
                formData.append("post_id", post.dataset.id);
            });
        },

        success: function () {
            console.log(this.files[0].xhr.responseText)
        }
    };

管理员控制器

public function storePostMedia(Request $request)
{
    // trying to get model by post type, there are several models depending by post types
    $table = $request->get("post_type");
    $model = getModel($table);
    // finding post
    $post = $model->find($request->get("post_id"));
    $media = new Media;
    // store images
    foreach ($request->file("images") as $image){
        $new_media = $media->storePostImages($image);
        $post->media()->save($new_media);
    }
}

storePostImages() 方法

public function storePostImages($file)
{
    // get image - rename - storage to storage folder
    $realName = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
    $extension = $file->getClientOriginalExtension();
    $new_name = str_slug($realName) . "-" . time() . "." . $extension;
    $fullPath = \Storage::putFileAs("posts", $file, $new_name);
    // save to database
    $this->name = $new_name;
    $this->path = $fullPath;

    return $this;
}

【问题讨论】:

  • 只是猜测,可能是时间函数每秒被多次点击,所以它不会在新文件名之间改变? $new_name = str_slug($realName) . "-" . time() . "." . $extension;
  • @ourmandave 上传的文件名称不同,时间加法可能相同,但文件末尾肯定有不同的名称

标签: php laravel laravel-5 dropzone.js polymorphic-associations


【解决方案1】:

我解决了为每条记录创建新模型实例的问题

foreach ($request->file("images") as $image){ 
    $media = new Media;
    $new_media = $media->storePostImages($image);
    $post->media()->save($new_media);
}

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2018-03-31
    • 2012-08-29
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2012-06-26
    • 2014-08-18
    相关资源
    最近更新 更多