Laravel数组如何保存到数据库

时间:2018-06-06 07:11:47

标签: php laravel eloquent

问题是我想将数组存储到数据库中,这样主题可以或多或少。

数据库选择表

|----|---------|----------|------------------|
| id | user_id | topic_id | question_number  |
|----|---------|----------|------------------|
|  1 |   1     |1st array |        21        |
|----|---------|----------|------------------|
|  2 |   1     |2nd array |        5         |
|----|---------|----------|------------------|
|  3 |   1     |3rd array |        3         |
|----|---------|----------|------------------|
..............................................
| 34 |   1     |34  array |        5         |
|----|---------|----------|------------------|

DD

array:3 [▼
"_token" => "HhR1wmjgJUvmnRsoYxcg3yezqzq7ORKqX6dAHzCD"
"time" => "30:01"
"number" => array:34 [▼
1 => "21"
2 => "5"
3 => "3"
4 => "0"
5 => "0"
6 => "0"
........
34 => "5"
]

控制器存储功能

public function store(Request $request){
    $time = $request->input('time');
    foreach ($request->input('number') as $key => $value) {
        Choice::create([
            'user_id' => Auth::id(),
            'time'  => $time,
            'topic_id' => $key,
        ]);
}}

1 个答案:

答案 0 :(得分:2)

public function store(Request $request) {
    $time = $request->input('time');
    foreach ($request->input('number') as $key => $value) {
        Choice::create([
            'user_id' => Auth::id(),
            'time'  => $time,
            'topic_id' => $key, // or  $key . 'st array';
            'question_number' => $value,
        ]);
    }
}}