首页 > 解决方案 > 如何在 Laravel 中存储 Select2 JS 中的数组值

问题描述

我正在使用 MySQL 数据库。我有多个值的 select2 js 这是我的代码

我的刀片视图和 JS

<input type="text" class="form-control tools_id" name="tools_id[]" multiple/>
var $tools_id = jQuery('.tools_id');
$tools_id.select2({
    multiple: true,
    placeholder: 'Tools',
    ajax: {
        url: 'sample/gettools',
        dataType: 'json',
        delay: 250,
        data: function (term, page) {
            return {
                q: term, //search term
            };
        },
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tools,
                        id: item.tools_id
                    }
                })
            };
        },
        cache: true
    }
});

我的模特

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sample extends Model
{
    protected $primaryKey = 'id';

    public $incrementing = false;

    protected $table = 'lab_sample';

    protected $casts = [
        'tools_id' => 'array'
    ];

    protected $fillable = ['name','summary','tools_id'];
}

我的控制器

public function store(Request $request)
{
    $sample = Sample::create([
        'name'     => $request->name,
        'summary'  => $request->summary,
        'tools_id' => $request->input('tools_id'),
    ]);

    return Response::json($sample);
}

我的代码已成功保存数据,但问题是当我选择多个值/标签时,它像这样保存了数组值(tools_id)

["20,21"]

它应该是这样的

["20","21"]

标签: laraveljquery-select2

解决方案


推荐阅读