插入忽略多个数组?

问题描述 投票:1回答:2

如何在DB :: Table之类的laravel中执行这样的查询?

INSERT IGNORE INTO 'banban' ('column') values('value1', 'value2')

DB::table('table')->insertIgnore( array(
   array('column'=>'value1',),
   array('column'=>'value2')
  )
)
laravel laravel-4
2个回答
0
投票

我不知道除了使用DB::raw()之外如何使用Fluent,但Eloquent有一个firstOrNew()

// Gets a user with fname of 'john' and lname of 'smith' or creates a new model and sets these properties.
$user = User::firstOrNew(['fname' => 'john', 'lname' => 'smith']);

// Lets say you want to activate john smith
$user->activated = true;

// Saves the new model or existing model (whatever it was)
$user->save();

0
投票

这是我在我的\ App \ Model的静态函数中使用的代码,用insert ignore添加多个值。这段代码是我在StackOverflow上遇到的不同答案的汇编。

使用PHP 7.1.3测试和使用Laravel 5.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)返回模型的新实例。这是在静态函数中获取Model表名的简单方法。

substr(...,0,-1)用于删除“值”的最新逗号

使用str_repeat两次创建“(?,?,?)”占位符和“?”内。

array_merge(...$values)奉承一系列价值观。这也是$values无法拥有自定义键的原因。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.