简体   繁体   English

Laravel:如何将多个select2下拉选择的数据插入mysql数据库?

[英]Laravel: How to insert multi select2 dropdown selected data to mysql database?

I am trying to insert data into database. 我正在尝试将数据插入数据库。 But i don't know how to insert multi select data into the mysql database. 但是我不知道如何将多个选择数据插入mysql数据库。

You have to to iterate through the multi select array then save one by one. 您必须遍历多重选择数组,然后逐个保存。

foreach ($_POST['your_key'] as $selectedOption) {
   // save $selectedOption to database
}

I am not quite sure what you mean by multi-select 我不太确定多选的意思

But I am going to tell you how to inset more than one row in a shot in database in Laravel. 但是我将告诉您如何在Laravel的数据库中插入多行。

First, You make an associative array of data you want to insert, which will contain column name as key and value as the value you want to insert. 首先,您要创建一个要插入的关联数据数组,该数组将包含列名作为键,并包含值作为要插入的值。 Lets say you have a table named users in which you want to insert 4 new rows with different names you got from your form: 假设您有一个名为users的表,要在其中插入4个新行,这些新行的名称是从表单中获得的:

$data = [
  ['name'=>'xxx'],
  ['name'=>'yyy'],
  ['name'=>'zzz'],
  ['name'=>'qqq']
];

Then you use model for that table(in our case: users) which will be most likely: User to insert data in one shot: 然后为该表(在我们的示例中为用户)使用模型,这很可能是:用户将数据插入一张照片:

User::insert($data);

Let's say you've got a table that have 2 columns : 假设您有一个包含2列的表:

CREATE TABLE table(
    id int not null primary key auto_increment,
    selectValue /*Whatever*/
)

And you've got a select named "MultipleValues[]" ( <select name='MultipleValues[]' multiple='multiple'/> ) so at your controller : 并且您有一个名为“ MultipleValues []”的<select name='MultipleValues[]' multiple='multiple'/><select name='MultipleValues[]' multiple='multiple'/> ),因此在您的控制器处:

public function update(Request $request)
{
    $insertData = [];
    $multipleValues = $request->get('MultipleValues');
    foreach($multipleValues as $value)
    {
        $insertData['selectValue'] = $value;
    }
    DB::table('table')->insert($insertData);
}

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

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