繁体   English   中英

如何将多选数据存储到数据库 laravel 5.5

[英]How to store multiselect data into the database laravel 5.5

我在 laravel 上的更新功能有问题,我正在尝试从表单中的多选发送数据,我希望“组合”的描述存储多个项目,并且我从另一个表中获取这些项目(productos)并将它们放在表单内的选择中。 但问题是,由于我要发送几个项目,我需要将它们作为数组发送以将其存储到数据库中,然后我得到错误

array to string conversion

这是我的控制器上的功能

public function update(Combos $product){

$data = request()->validate([
    'name' => 'required|string|min:8|max:100',
    'id' => 'required',
    'description' =>'required',
]);

$user->where('id',$data['id'])->update($data);

return view('Combos')->with('combos', Combos::all())
                     ->with('products', Products::all());
}

由于我通过表单中的选择发送值:

<div class="form-group" id="selector">
<label for="">Products</label>
<select multiple="multiple" class="form-control" name="description[]" >
<option value="" disabled>Select product</option>
@foreach ($products as $product)
<option value="{{$product->name}}">{{$product->name}}</option>
@endforeach
</select>
</div>  

有什么办法可以将数据列表作为字符串传递(因为数据库上的列是字符串)。 我尝试通过将 $data['description] 放在这样的变量中来使用 implode():

public function update(Combos $product){

$data = request()->validate([
    'name' => 'required|string|min:8|max:100',
    'id' => 'required',
    'description' =>'required',
]);

$new_desc = implode(" ", $data['description']);
dd($new_desc); //prints "value1 value2 value3" as string, instead of an array

$product->where('id',$data['id'])->update($data);

return view('Combos')->with('combos', Combos::all())
                     ->with('products', Products::all());
}

奇怪的是,当我dd($new_desc)它确实将数组转换为字符串

或者直接将data['description]放在implode()中,但即使那样它也不起作用。

public function update(Combos $product){

$data = request()->validate([
    'name' => 'required|string|min:8|max:100',
    'id' => 'required',
    'description' =>'required',
]);

implode(" ", $data['description']); 
dd($data['description']); //when I submit the update it still sends the data as an array array:2[0 => 'value1', 1 => value2]

$user->where('id',$data['id'])->update($data);

return view('Combos')->with('combos', Combos::all())
                     ->with('products', Products::all());
}

在这种情况下,我该怎么做才能将多选中的项目列表作为字符串而不是数组发送,或者如何在发送更新之前将它们转换为字符串? 如果有人可以帮助我,我将非常感激,在此先感谢。

您可以使用 laravel casts将数组转换为 JSON(字符串)并存储到数据库中,当您从 DB 获取数据时,它将再次转换为数组,因此您可以使用它来显示多选中的选定项目

class Combos extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'description' => 'array',
    ];
}

此功能也适用于 laravel 5.5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM