简体   繁体   中英

Laravel array how to save to database

Question is I want to store that array to database to like this and topics can be more or less.

Database Choice table

|----|---------|----------|------------------|
| 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"
]

Controller store function

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,
        ]);
}}
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,
        ]);
    }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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