gpt4 book ai didi

php - 使用 Laravel 的 Fluent 插入忽略

转载 作者:IT王子 更新时间:2023-10-29 00:34:57 29 4
gpt4 key购买 nike

有没有一种快速的方法来修改 Laravel's Fluent 生成的 SQL 查询?有一个 INSERT IGNORE 而不是通常的 INSERT

我正在尝试插入一个包含五十个元素的数组。手动写出整个查询将使代码膨胀并使其更容易出现人为错误。

最佳答案

在你的模型中试试这个魔法:

public static function insertIgnore($array){
$a = new static();
if($a->timestamps){
$now = \Carbon\Carbon::now();
$array['created_at'] = $now;
$array['updated_at'] = $now;
}
DB::insert('INSERT IGNORE INTO '.$a->table.' ('.implode(',',array_keys($array)).
') values (?'.str_repeat(',?',count($array) - 1).')',array_values($array));
}

像这样使用:

Shop::insertIgnore(array('name' => 'myshop'));

如果“名称”属性是唯一键,这是防止在多用户环境中使用 firstOrCreate 可能发生的约束冲突的好方法。

关于php - 使用 Laravel 的 Fluent 插入忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12622341/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com