Laravel - 将多个数据保存到数据库中的一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47102608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:54:47  来源:igfitidea点击:

Laravel - Save multiple data to one column in database

phpmysqllaravel

提问by universal

I have a student form on Laravel 5.5 where users can add as many hobbies as they can. Each hobby has Title, Description & Image. I want to save all Hobbies. How can I save these information?

我在 Laravel 5.5 上有一个学生表格,用户可以在其中添加尽可能多的爱好。每个爱好都有标题、描述和图片。我想保存所有Hobbies. 如何保存这些信息?

enter image description here

在此处输入图片说明

My view

我的看法

<form action="/" method="post" enctype="multipart/form-data" files="true">
<input name="feat[]" type="text" placeholder="Feat 1">
<textarea name="feat_desc[]" placeholder="Feat 1 Desc">
<input type="file" name="feat_img[]">

<input name="feat2" type="text" placeholder="Feat 2">
<textarea name="feat2desc" placeholder="Feat 2 Desc">
<input type="file" name="feat2img">

<button>Add New Hobby</button>

JQuery for dynamic fields

用于动态字段的 JQuery

$('#add-form').click(function() {
   i++;
    $('#add-me').append(

            '<input id="quantity" type="text" name="feat[]">'
            '<textarea name="feat_desc[]">'
            '<input type="file" name="feat_img[]">'
    );

});

});

My Controller:

我的控制器:

public function create($Request $requst, Student $student)
$posts = Student::create([
        'name' => request('name'),
        'interests' => request('interests'),
        'hobbies' => json_encode(request('hobbies')),
        ]);

    return redirect ('/');

My database migration

我的数据库迁移

{
    Schema::create('students', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('interests');
        $table->text('hobbies');
        $table->timestamps();
    });
}

采纳答案by spirit

UPDATED ANSWER:I strongly recommend you to record each hobby in a separate table, because it is more clear and is better for search and indexing. you may have the second table hobbieslike this:

更新的答案:我强烈建议您将每个爱好记录在一个单独的表中,因为它更清晰,更适合搜索和索引。你可能有这样的第二桌爱好

Schema::create('student_hobbies', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('student_id')->unsigned();
    $table->string('title');
    $table->text('description');
    $table->string('path');
    $table->timestamps();
});

And then save each hobby in a new record with its student_id. in this case you can also save images into database instead of saving them on a separate storage. see this threadfor more information.

然后使用其 student_id 将每个爱好保存在一个新记录中。在这种情况下,您还可以将图像保存到数据库中,而不是将它们保存在单独的存储中。有关更多信息,请参阅此线程

Anyway if you decided to put all these info in a single field, do the following:

无论如何,如果您决定将所有这些信息放在一个字段中,请执行以下操作:

First of all, loop through the request, save files to a proper location with a unique name,and combine your hobbies Then save the hobbies to database using json_encode:

首先,遍历请求,将文件以唯一名称保存到适当的位置,并结合您的爱好,然后使用json_encode将爱好保存到数据库:

public function create($Request $requst, Student $student)
    $hobbies = [];
    $images = $request->file('feat_img');
    $descriptions = $request->feat_desc;
    foreach ($request->feat as $key => $title) {
        $filename = '';
        if (!empty($files[$key]) && $files[$key]->isValid()) {
            $filename = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
            $files[$key]->move(storage_path('images'), $filename);
        }
        $hobbies[] = [
            'title' => $title,
            'desc' => $description[$key],
            'image' => $filename,
        ];
    }
    $posts = Student::create([
        'name' => request('name'),
        'interests' => request('interests'),
        'hobbies' => json_encode($hobbies),
    ]);
}


PREVIOUS ANSWER:You may save multiple data to a single column using CSV or JSON encoding form:

以前的答案:您可以使用 CSV 或 JSON 编码形式将多个数据保存到单个列中:

public function create($Request $requst, Student $student)
$posts = Student::create([
        'name' => request('name'),
        'interests' => request('interests'),
        'hobbies' => json_encode(request('hobbies')), // implode(',', request('hobbies'))
        ]);
return redirect ('/');

In the HTML, hobbiesshould look something like this:

在 HTML 中,爱好应该是这样的:

<input name="hobbies[]" />
<input name="hobbies[]" />
...

回答by wahyzcrak

https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

It sounds like you may want use attribute casting to store the data as json that can be serialized and deserialized as array.

听起来您可能希望使用属性转换将数据存储为可以序列化和反序列化为数组的 json。