如何将sql查询转换为laravel ORM查询,如果不存在则插入

时间:2019-06-28 20:31:27

标签: php sql laravel

    public function update_tb_tokenidparc($token, $id_vendedor_pr, $id_corretora_pr, $id_parceiro){" INSERT INTO tb_tokenidparc 
    (nu_cdVendedor4E_tk1,nu_cdCorretoraS4E_tk,nu_IdParceiro_tk,cd_Codtokenidparc,status_token)
    SELECT * FROM (SELECT $id_vendedor_pr,$id_corretora_pr,$id_parceiro,$token,'1') AS tmp
    WHERE NOT EXISTS (
        SELECT * FROM tb_tokenidparc WHERE nu_cdVendedor4E_tk = $id_vendedor_pr and nu_cdCorretoraS4E_tk = $id_corretora_pr
        and nu_IdParceiro_tk = $id_parceiro and cd_Codtokenidparc = '.$token.') LIMIT 1)";

我有这个模型,需要将其转换为laravel orm

最大的问题是我在laravel文档中没有找到的不存在子句

如果我喜欢这样的东西

我不是要插入或创建,因为这不能解决我的问题

编辑¹:进行转换的原因是因为我要传递一个数组。

编辑²:我已经尝试过的

public function insert_tb_tokenidparc($token, $id_vendedor_pr, $id_corretora_pr, $id_parceiro){

        DB::table('tb_tokenidparc')->firstOrCreate([
            'nu_cdVendedor4E_tk' => $id_vendedor_pr,
            'nu_cdCorretoraS4E_tk' => $id_corretora_pr,
            'nu_IdParceiro_tk' => $id_parceiro,
            'cd_Codtokenidparc' => $token,
            'status_token' => '1',
        ]);

    }

1 个答案:

答案 0 :(得分:0)

您可以为firstOrCreate方法提供两个参数:第一个参数应包含要查找的列/值对,第二个参数应包含要在第一列时插入的任何其他列/值对数据库中找不到/ value对。

在您的情况下,您似乎要查找除status_token值以外的所有列,因此可以将firstOrCreate方法的用法稍微更改为:

 TbTokenidparc::firstOrCreate([
            'nu_cdVendedor4E_tk' => $id_vendedor_pr,
            'nu_cdCorretoraS4E_tk' => $id_corretora_pr,
            'nu_IdParceiro_tk' => $id_parceiro,
            'cd_Codtokenidparc' => $token,
        ], [
            'status_token' => '1',
        ]);

假设TbTokenidparc表的tb_tokenidparc为雄辩模型。如果尚未定义模型,则可以这样定义:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TbTokenidparc extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tb_tokenidparc';

     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['nu_cdVendedor4E_tk1', 'nu_cdCorretoraS4E_tk', 'nu_IdParceiro_tk', 'cd_Codtokenidparc', 'status_token'];
}