Php 如何在Laravel中插入具有多个不同列的多行

Php 如何在Laravel中插入具有多个不同列的多行,php,mysql,laravel,laravel-5.6,Php,Mysql,Laravel,Laravel 5.6,我刚刚尝试了下面的命令,收到了不想要的结果 DB::table('locations')->insert([ ['code' => 'YC', 'name' => 'York Clifton'], ['code' => 'YK', 'name' => 'York'], ['postcode' => 'DR1', 'name' => 'Jason'], ['postcode' => 'DLR', 'name' =

我刚刚尝试了下面的命令,收到了不想要的结果

DB::table('locations')->insert([
    ['code' => 'YC', 'name' => 'York Clifton'],
    ['code' => 'YK', 'name' => 'York'],

    ['postcode' => 'DR1',  'name' => 'Jason'],
    ['postcode' => 'DLR',  'name' => 'Beckton']
]);
上述内容将在表格中插入如下数据:

预期实际值
+-----+--------------+------+----------+        +----+--------------+------+----------+
|id |姓名|代码|邮政编码| id |姓名|代码|邮政编码|
+-----+--------------+------+----------+        +----+--------------+------+----------+
|1 |约克·克利夫顿| YC | NULL | 1 |约克·克利夫顿| YC | NULL|
|2 | York | YK | NULL | 2 | York | YK | NULL|
|3 | Jason | NULL | DR1 | 3 | DR1 | Jaso | NULL|
|4 |贝克顿|零| DLR | 4 | DLR |贝克|零|
+-----+--------------+------+----------+        +----+--------------+------+----------+
位置表是使用以下代码段生成的:

$table->string('name', 100);
$table->string('code', 4)->nullable();
$table->string('postcode', 10)->nullable();
当然,我想要的结果是在数据库中插入四行;前两个将填充
code
name
字段,而后两个插入将填充
postcode
name

我已经看过文件,上面说:

查询生成器还提供了一种插入方法,用于将记录插入到数据库表中。insert方法接受列名和值的数组:

您甚至可以通过一次调用向表中插入多条记录,通过传递数组数组来插入。每个数组表示要插入到表中的行

我不完全确定Laravel到底在做什么,但它似乎预先构建了insert语句,然后插入数据,忽略了列名键。
为了避免这个问题,我只是用不同的列名分隔了insert语句。
这让我想到,如果列键是多余的(第一个数组中的键除外),为什么还要为所有记录设置列键呢?为什么insert方法没有两个参数;一个包含列名数组,另一个包含数据


文档中并没有说数组键必须是相同的,所以如果我遗漏了一些东西,如果有人能提供一些关于为什么这不起作用的见解,我将不胜感激

tl;博士
当使用不同的列名时,如何在表中插入多行?

查看Laravel的代码,就知道了这种行为的原因。显然,Laravel将insert查询编译为批处理insert,而不是作为每个传递数组的单独insert查询

在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调用将执行查询:

INSERT INTO `locations` (`code`, `name`) 
VALUES ('YC', 'York Clifton'), 
       ('YK', 'York'),
       ('DR1', '...')
但是,您可以通过一次调用插入所有条目,方法是在locations表中指定所有列:

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是什么版本吗?你导入了DB facade吗?即
使用DB@TahirAfridi该版本在问题-Laravel 5.6下标记。是的,我用的是正面。我没有得到一个错误,只是不受欢迎的行为