【问题标题】:How to apply 'ON CONFLICT' condition while Inserting records after SELECT statement in Laravel?如何在 Laravel 中的 SELECT 语句后插入记录时应用“ON CONFLICT”条件?
【发布时间】:2020-04-09 23:04:36
【问题描述】:

下面是需要 Laravel 查询的 SQL 查询。

    INSERT INTO 'details' (id, contact) 
    SELECT DISTINCT tmp_details.id, students.contact 
    FROM 'tmp_details'
    INNER JOIN 'students' USING(name) 
    ON CONFLICT DO NOTHING;    

我无法应用ON CONFLICT 条件。

我已将其部分转换如下。

    $strSQL =  DB::table('tmp_details')
                ->join('students', 'tmp_details.name', '=', 'students.name')
                ->select('tmp_details.id','students.contact');
               DB::table('details')->insertUsing(['id', 'contact'], $strSql);

【问题讨论】:

  • 不确定但试试insertOrIgnore
  • 我尝试使用 insertOrIgnore,但出现如下错误: SQLSTATE[42703]: Undefined column: 7 ERROR: column "0" of relationship "details" does not exist LINE 1: insert into "details " ("0", "1") 冲突时的值 ($1, $2)... ^ (SQL: insert into "details" ("0", "1") 冲突时的值 (id, contact) 什么都不做)
  • 显示您的查询。
  • DB::table('details')->insertOrIgnore(['id', 'contact'], $strSql); //relapced only insertUsing 我无法插入记录,可能是参数必须是一个数组并且值不应该在变量中给出。
  • 我会研究现成的解决方案:github.com/staudenmeir/laravel-upsert

标签: php laravel lumen


【解决方案1】:

不确定,但试试这个。

$strSQL =  DB::table('tmp_details')
              ->join('students', 'tmp_details.name', '=', 'students.name')
              ->pluck('tmp_details.id','students.contact');

DB::table('details')->insertOrIgnore($strSql);

【讨论】:

    【解决方案2】:

    尝试使用DB::select()声明:

    DB::select("
        INSERT INTO 'details' (id, contact) 
        SELECT DISTINCT tmp_details.id, students.contact 
        FROM 'tmp_details'
        INNER JOIN 'students' USING(name) 
        ON CONFLICT DO NOTHING;
    ");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2015-05-30
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      相关资源
      最近更新 更多