我写这个函数是为了从数组中插入单词:
public function ins($array)
{
foreach ($array as $key => $value) {
DB::table('words')->updateOrInsert(['word' => $value]);
}
}我使用下面的查询为mysql中的重复值创建了索引:
CREATE UNIQUE INDEX `idx_word` ON `db`.`words` (word);但是当我使用我的函数来添加单词时,会出现这个错误:
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where (`word` = ?) limit 1' at line 1 (SQL: update `words` set where (`word` = microsoft) limit 1) ◀"如何在Laravel 5.5中正确地将不重复的单词添加到数据库?
发布于 2017-10-18 01:33:36
下面是updateOrInsert的方法签名
bool updateOrInsert(array $attributes, array $values = [])如果行属性已经存在(在本例中,如果单词已经存在),它将根据传递给第二个参数的内容进行更新。
要解决您的问题,只需重复attributes参数来填充values参数:
DB::transaction(function () use ($value) {
DB::table('words')->updateOrInsert(['word' => $value], ['word' => $value]);
});发布于 2017-10-18 01:37:41
我认为你应该使用模型而不是查询构建器,比如DB::table。
Word.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Word extends Model
{
protected $table = "words";
}在Word模型上使用updateOrCreate,如下所示。
Word::updateOrCreate(['word' => $value]);注意:未经过测试,给出了一个大纲。
发布于 2017-10-18 01:37:10
你可以这样做:
public function ins($array)
{
$wordsNotExists = array();
$wordsToInsert = array();
$array = array_unique($array);
$wordsThatExists = DB::table('words')
->whereIn('word', $array)
->pluck('word');
$wordsNotExists = array_diff ($array, $wordsThatExists->toArray());
foreach ($wordsNotExists as $key => $value) {
$wordsToInsert[] = ['word' => $value];
}
DB::table('words')->insert($wordsToInsert);
}创建索引后,您可以使用Raw方法插入数据:
foreach (array_unique($array) as $key => $value) {
DB::insert('INSERT INTO words VALUES (?) ON DUPLICATE KEY word = VALUES(word)', $value);
}https://stackoverflow.com/questions/46795811
复制相似问题