php - Laravel Form::select multiple,保存所有选定字段的数组或列表,而不仅仅是最后选择的字段

标签 php mysql arrays forms laravel-4

嗯,我遇到了奇怪的事情,要么到目前为止没有人注意到,要么无法从 laravel 中的选择框保存。

我正在创建一个类别,这些类别将按类型分隔,但主要问题是我不想将 Form::selectmultiple 选项一起使用能够选择多个类别,但在提交时 laravel 仅保存最后选择的字段的字符串,那么如果 laravel 仅保存最后选择的字段,为什么还会存在 multiple

这是我的代码示例

{{ Form::select('categories[1]', $platform, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[2]', $developer, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[3]', $publisher, null, ['multiple'=>true, 'class' => 'form-control']) }}

我在 Controller 中定义了 $developer、$publisher 和 $platform,这基本上是特定 id 下的类别列表。

$platform = Category::->where('type', '=', 1)->lists('name', 'id');

因此,这将返回 View 的所有类别的数组。

----------------
| name    | id |
----------------
| Windows |  1 |
----------------
| Linux   |  2 |
----------------
| MacOS   |  3 |
----------------

所以到目前为止,这一切都工作正常,在我的网页中,我在带有多个选择的选择框中有一个我想要的类别列表

问题是保存时它只保存选择框中最后选定的字段的字符串。

提交后我得到了这个

["categories"]=> //This is as expected as i have 3 selects in an array
    array(2) {
      [1]=> // and this is id of first select box and category
          string(1) "3" // and this is the problem, read below please
      [2]=> // and this is id of second select box and category
          string(1) "4"
    }

所以问题是,正如你所看到的,我得到了一个数字为 3 的字符串。该数字实际上代表了最后选定字段的 id,在本例中,我选择了 id 为 3 的 MacOS

我需要得到的是:

["categories"]=>
    array(2) {
      [1]=>
          string(1) "1,3"
      [2]=> 
          string(1) "4"
    }

这意味着我选择了 WindowsMacOS,稍后我可以获取该字符串并按该 id 分解每个类别。

或者

["categories"]=>
    array(2) {
      [1]=>
          array(2) {
             [0]=> 1
             [1]=> 3
          }
      [2]=> 
          array(1) {
             [0]=> 4
          }
    }

有什么办法可以让它发挥作用吗?

最佳答案

我忘记说了,我习惯了使用wordpress进行这种工作,很容易用一个查询查询所有数据,这就是所谓的多维数组。

我实际上是通过反复试验弄清楚的,我记得在 wordpress 中使用多维数组时,你必须用括号定义每个数组,它将生成一棵树,这里是同样的事情,所以正确的代码是:

 {{ Form::select('categories[1][]', $platform, null, ['multiple'=>true, 'class' => 'form-control']) }} 
 {{ Form::select('categories[2][]', $developer, null, ['multiple'=>true, 'class' => 'form-control']) }} 
 {{ Form::select('categories[3][]', $publisher, null, ['multiple'=>true, 'class' => 'form-control']) }}

它将把它保存在数组中,如下所示:

["categories"]=>
array(2) {
  [1]=>
      array(2) {
         [0]=> 1
         [1]=> 3
      }
  [2]=> 
      array(1) {
         [0]=> 4
      }
}

关于php - Laravel Form::select multiple,保存所有选定字段的数组或列表,而不仅仅是最后选择的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28467584/

相关文章:

php - 如何检查 PHP 中的每个字符是否都是字母数字?

MYSQL 日期时间四舍五入到最近的时间

Java 空指针异常

arrays - 如何将命令输出存储到 Ansible 中的数组中?

php - 找不到类 'HTML'(查看 : C:\xampp\htdocs\laravel_demo\resources\views\pages\registration. blade.php)

php - 使用 DOMDocument 创建复杂结构

mysql - AR 获取自己的帖子和 friend 的帖子

c# - 计算datagridview中相似单元格值的总和

java - 获取枚举值数组减去指定项

php - 多语言 URL 结构上的重复内容