php – 如何在Laravel中插入多个具有多个不同列的行
作者:互联网
我刚刚尝试了以下命令并收到了不良结果.
DB::table('locations')->insert([
['code' => 'YC', 'name' => 'York Clifton'],
['code' => 'YK', 'name' => 'York'],
['postcode' => 'DR1', 'name' => 'Jason'],
['postcode' => 'DLR', 'name' => 'Beckton']
]);
以上内容将在表格中插入数据:
Expected Actual
+-----+--------------+------+----------+ +----+--------------+------+----------+
| id | name | code | postcode | | id | name | code | postcode |
+-----+--------------+------+----------+ +----+--------------+------+----------+
| 1 | York Clifton | YC | NULL | | 1 | York Clifton | YC | NULL |
| 2 | York | YK | NULL | | 2 | York | YK | NULL |
| 3 | Jason | NULL | DR1 | | 3 | DR1 | Jaso | NULL |
| 4 | Beckton | NULL | DLR | | 4 | DLR | Beck | NULL |
+-----+--------------+------+----------+ +----+--------------+------+----------+
位置表使用以下代码段构建:
$table->string('name', 100);
$table->string('code', 4)->nullable();
$table->string('postcode', 10)->nullable();
当然,我希望的结果是在数据库中插入四行;前两个将填充代码和名称字段,而后两个插入将填充邮政编码和名称.
我查看了文档说:
The query builder also provides an insert method for inserting records into the database table. The insert method accepts an array of column names and values:
You may even insert several records into the table with a single call to insert by passing an array of arrays. Each array represents a row to be inserted into the table.
我不完全确定Laravel在幕后做了什么,但它似乎预先构建了insert语句,然后插入数据,忽略了列名键.
为了避免这个问题,我只是将insert语句与不同的列名分开.
这让我想一想,如果所有记录的列密钥多余(除了第一个数组中的键),为什么还要为所有记录添加列密钥?为什么没有insert方法的两个参数;一个具有列名称数组,另一个具有数据.
文档并没有说数组键必须都是相同的,所以如果我遗漏了某些东西,那么如果有人能够提供一些有关为什么这不起作用的见解,我将不胜感激.
TL;博士
使用不同的列名称时,如何在表中插入多行?
解决方法:
看看Laravel的代码刚才看到了这种行为的原因.显然,Laravel将插入查询编译为批量插入,而不是作为每个传递的数组的单独插入查询.
在insert方法中,您可以看到如何生成查询:
$sql = $this->grammar->compileInsert($this, $values);
如果您在compileInsert方法中更进一步,您会注意到查询的列是从仅传递的第一个数组生成的:
$columns = $this->columnize(array_keys(reset($values)));
// We need to build a list of parameter place-holders of values that are bound
// to the query. Each insert should have the exact same amount of parameter
// bindings so we will loop through the record and parameterize them all.
$parameters = [];
foreach ($values as $record) {
$parameters[] = '('.$this->parameterize($record).')';
}
$parameters = implode(', ', $parameters);
return "insert into $table ($columns) values $parameters";
所以基本上,你的插入调用将执行查询:
INSERT INTO `locations` (`code`, `name`)
VALUES ('YC', 'York Clifton'),
('YK', 'York'),
('DR1', '...')
但是,您可以通过提供位置表中的所有列,通过单个调用插入所有条目:
DB::table('locations')->insert([
['code' => 'YC', 'name' => 'York Clifton', 'postcode' => null],
['code' => 'YK', 'name' => 'York', 'postcode' => null],
['code' => null, 'name' => 'Jason', 'postcode' => 'DR1'],
['code' => null, 'name' => 'Beckton', 'postcode' => 'DLR']
]);
标签:laravel-5-6,php,laravel,mysql 来源: https://codeday.me/bug/20190828/1746982.html