Laravel 5.1检索多个输入值并插入到db

时间:2016-04-28 06:12:43

标签: php mysql laravel-5.1

我有一个名为category的输入表单,当你提出问题时,它可以在stackoverflow中的tags输入表单中有多个值 我想从该表单中获取所有输入值并将其插入category_service数据透视表中 我使用$category = implode(",", Input::get('category'));来获取数组值
尝试使用此代码插入时,我得到Invalid argument supplied for foreach()错误:

foreach ($category as $category) {
    DB::insert('INSERT INTO category_service (category_id, service_id) VALUES (?,?)', array('$category', $service->id));
}

表格如下:

category_table
+----+--------------+
| id |   category   |
+----+--------------+
|  1 |  category_1  |
|  2 |  category_2  |
+----+--------------+

service_table
+----+--------------+
| id |   service    |
+----+--------------+
|  1 |   service_1  |
+----+--------------+

category_service_table //pivot table to store category id and service id
+----+--------------+-------------+
| id | category_id  |  service_id |
+----+--------------+-------------+
|  1 |      1       |      1      |
|  2 |      2       |      1      |
+----+--------------+-------------+

var_dump结果为string(3) "2,1"

2 个答案:

答案 0 :(得分:1)

$category = implode(",", Input::get('category'));

implode从数组

中创建字符串

$category = Input::get('category'); if (!empty($category) && is_array($category)) { foreach ($category as $val) { DB::insert('INSERT INTO category_service (category_id, service_id) VALUES (?,?)', array((int) $val, $service->id)); } }

答案 1 :(得分:0)

使用PHP implode函数,您将数组连接到字符串并将字符串传递给foreach,结果Invalid argument supplied for foreach()错误。你和explode混淆了吗?请参阅官方文档。 ImplodeExplode。此外,最好在foreach中使用复数和单数命名,例如foreach ($categories as $category)

对于Laravel插入使用:

DB::table('category_service')->insert(
  ['category_id' => $category, 'service_id' => $service->id]
);

此外,您将$category放在单引号中,变量将不会执行,它将作为字符串传递。

另外,你得到了$service->id