我正在使用MySQL数据库。我有多个值的select2 js 这是我的代码
我的Blade视图和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"]