gpt4 book ai didi

mysql - laravel 在插入之前检查记录是否存在,有效的方法

转载 作者:行者123 更新时间:2023-11-29 01:57:18 25 4
gpt4 key购买 nike

假设我有包含这些数据的名为组的表:

+----+---------+------+-------+| id | user_id | name | color |+----+---------+------+-------+|  1 |       1 | foo  | green ||  2 |       1 | bar  | red   ||  3 |       1 | baz  |       ||  4 |       2 | baz  | grey  ||  5 |       3 | foo  | blue  ||  6 |       3 | baz  |       ||  7 |       4 | baz  | brown ||  8 |       4 | foo  |       ||  9 |       4 | qux  | black |+----+---------+------+-------+

I'm going to read a csv file and convert it to an array of data like this:

[
[
'user_id' => 2,
'name' => 'foo'
],
[
'user_id' => 2,
'name' => 'bar'
],
[
'user_id' => 2,
'name' => 'baz'
],
[
'user_id' => 2,
'name' => 'qux'
],
[
'user_id' => 2,
'name' => 'tux'
],
]

并且只将新数据插入数据库,并跳过数据库中已经存在的数据,在本例中,为用户 2 组 baz

在 Eloquent 中有一些有用的方法,比如 firstOrCreate()findOrNew() 似乎是我需要的,但这些方法只针对一条记录,并且如果我使用它们,我应该按文件行运行它们。

while($line = $this->decoder->decode($this->file) {
$row = Group::firstOrCreate($line);
}

运行更少的查询是否有更好的解决方案?

最佳答案

在重复 key 更新时使用 INSERT ...

INSERT INTO table (user_id,name) VALUES(1, "test") ON DUPLICATE KEY UPDATE name=VALUES(name)

对于 Laravel 检查 this question

关于mysql - laravel 在插入之前检查记录是否存在,有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306762/

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