【问题标题】:How to check if the record is exist or not in database using laravel?如何使用laravel检查记录是否存在于数据库中?
【发布时间】:2019-01-25 02:03:20
【问题描述】:

我尝试检查记录是否不存在,然后我将插入,但它不起作用。这是我的代码:

//check if nomor permohonan is exist
        $data_pemohon = DB::table('data_pemohon')->select('*')->where('noper', $noper)->get();
        if(is_null($data_pemohon)){
            return response(null);          
        }else{
            $data_antrian   = DB::table('antrian_sp')->select('*')->where('noper', $noper)->first();
            if(is_null($data_antrian)){
                $nama        = DB::table('data_pemohon')->select('nama')->where('noper', $noper)->first();
                $status      = DB::table('data_pemohon')->select('status_paspor')->where('noper', $noper)->first();
                $data       = array('tanggal'=>$tanggal, 'jam'=>$jam, 'noper'=>$noper, 'nama'=>$nama->nama, 'status'=>$status->status_paspor);
                $add_antrian= DB::table('antrian_sp')->insert($data);

                if($add_antrian){
                    return response($data_pemohon);
                }else{
                    echo "error";           
                }
            }else{
                return response(1); 
            }
        }

【问题讨论】:

  • 你可以查看这个链接-> stackoverflow.com/questions/27095090/…
  • 你得到的结果也请提及。
  • 我尝试检查记录是否不存在,然后我将执行插入 只是一条建议,如果您通过代码执行此操作,则必须处理并发。您的$data_antrian 可能在同时执行的代码中有欺骗,您可以使用noper 作为主键 以确保只创建一个。另外,我对$data_pemohon 很好奇,因为->get() 将返回空集合而不是 null,以防它没有结果 cmiiw。
  • 如果记录存在?要更新吗?

标签: laravel select insert


【解决方案1】:

不知道你为什么使用 DB 外观而不是 Eloquent:

$data_antrian = App\Antrian_sp::where('noper', $noper)->firstOrFail();

如果您没有 antrian_sp 表的模型或者只是更喜欢 DB 外观,那么应该这样做:

if ($data_antrian)

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多