首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更正我的函数- Laravel-5.5?

如何更正我的函数- Laravel-5.5?
EN

Stack Overflow用户
提问于 2017-10-18 01:24:57
回答 3查看 520关注 0票数 0

我写这个函数是为了从数组中插入单词:

代码语言:javascript
复制
public function ins($array)
{
    foreach ($array as $key => $value) {
        DB::table('words')->updateOrInsert(['word' => $value]);
    }

}

我使用下面的查询为mysql中的重复值创建了索引:

代码语言:javascript
复制
CREATE UNIQUE INDEX `idx_word` ON `db`.`words` (word);

但是当我使用我的函数来添加单词时,会出现这个错误:

代码语言:javascript
复制
"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中正确地将不重复的单词添加到数据库?

EN

回答 3

Stack Overflow用户

发布于 2017-10-18 01:33:36

下面是updateOrInsert的方法签名

代码语言:javascript
复制
bool updateOrInsert(array $attributes, array $values = [])

如果行属性已经存在(在本例中,如果单词已经存在),它将根据传递给第二个参数的内容进行更新。

要解决您的问题,只需重复attributes参数来填充values参数:

代码语言:javascript
复制
DB::transaction(function () use ($value) {
    DB::table('words')->updateOrInsert(['word' => $value], ['word' => $value]);
});
票数 5
EN

Stack Overflow用户

发布于 2017-10-18 01:37:41

我认为你应该使用模型而不是查询构建器,比如DB::table。

Word.php

代码语言:javascript
复制
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Word extends Model
{
    protected $table = "words";
}

Word模型上使用updateOrCreate,如下所示。

代码语言:javascript
复制
Word::updateOrCreate(['word' => $value]);

注意:未经过测试,给出了一个大纲。

票数 2
EN

Stack Overflow用户

发布于 2017-10-18 01:37:10

你可以这样做:

代码语言:javascript
复制
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方法插入数据:

代码语言:javascript
复制
foreach (array_unique($array) as $key => $value) {
    DB::insert('INSERT INTO words VALUES (?) ON DUPLICATE KEY word = VALUES(word)', $value);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46795811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档