Laravel 插入忽略多个数组?
如何使用DB::Table或类似的工具在laravel中执行这样的查询Laravel 插入忽略多个数组?,laravel,laravel-4,Laravel,Laravel 4,如何使用DB::Table或类似的工具在laravel中执行这样的查询 INSERT IGNORE INTO 'banban' ('column') values('value1', 'value2') DB::table('table')->insertIgnore( array( array('column'=>'value1',), array('column'=>'value2') ) ) 除了使用DB::raw(),我不知道如何使用Fluent实现
INSERT IGNORE INTO 'banban' ('column') values('value1', 'value2')
DB::table('table')->insertIgnore( array(
array('column'=>'value1',),
array('column'=>'value2')
)
)
除了使用
DB::raw()
,我不知道如何使用Fluent实现这一点,但Eloquent有一个firstOrNew()
下面是我在my\App\Model的静态函数中使用的代码,用于使用insert ignore添加多个值。这段代码是我在StackOverflow上遇到的不同答案的汇编 使用PHP7.1.3在Laravel5.6上进行测试和工作
$keys = ['column1', 'column2', 'column3'];
foreach ($whatever as $result) {
$banban = [];
$banban[] = $result->value1;
$banban[] = $result->value2;
$banban[] = $result->value3;
$values[] = $banban;
}
return DB::insert(
'INSERT IGNORE INTO ' . with(new self)->getTable() .
'(' . implode(',', $keys) . ') values ' .
substr(str_repeat('(?' . str_repeat(',?', count($keys) - 1) . '),', count($values)), 0, -1),
array_merge(...$values)
);
一些解释:
with(new self)
返回模型的新实例。在静态函数中获取模型表名是一种简单的方法
substr(…,0,-1)
用于删除“值”的最新逗号
stru repeat
用于两次创建“(?,?,?)”占位符和内部的“?”
array\u merge(…$values)
调整值数组。这也是为什么$values
不能有自定义键的原因
希望这有帮助
$keys = ['column1', 'column2', 'column3'];
foreach ($whatever as $result) {
$banban = [];
$banban[] = $result->value1;
$banban[] = $result->value2;
$banban[] = $result->value3;
$values[] = $banban;
}
return DB::insert(
'INSERT IGNORE INTO ' . with(new self)->getTable() .
'(' . implode(',', $keys) . ') values ' .
substr(str_repeat('(?' . str_repeat(',?', count($keys) - 1) . '),', count($values)), 0, -1),
array_merge(...$values)
);