จะตรวจสอบได้อย่างไรว่ามีบันทึกอยู่ในฐานข้อมูลโดยใช้ laravel?

ฉันพยายามตรวจสอบว่าไม่มีบันทึกอยู่หรือไม่ จากนั้นฉันจะทำการแทรก แต่มันใช้งานไม่ได้ นี่คือรหัสของฉัน:

//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); 
            }
        }

person Muhammad Haryadi Futra    schedule 18.08.2018    source แหล่งที่มา
comment
คุณสามารถตรวจสอบลิงค์นี้-> stackoverflow.com/questions/ 27095090/   -  person Payal Pandav    schedule 18.08.2018
comment
สิ่งที่คุณได้รับโปรดระบุด้วย   -  person Hidayat Ullah    schedule 18.08.2018
comment
ฉันพยายามตรวจสอบว่าไม่มีบันทึกอยู่หรือไม่ ฉันจะทำการแทรกเพียงคำแนะนำบางส่วน หากคุณทำสิ่งนี้ด้วยโค้ด คุณจะต้องจัดการกับการทำงานพร้อมกัน $data_antrian ของคุณอาจมีการซ้ำซ้อนกับโค้ดที่ทำงานในเวลาเดียวกัน คุณสามารถใช้ noper เป็น คีย์หลัก เพื่อให้แน่ใจว่ามีการสร้างคีย์เดียวเท่านั้น นอกจากนี้ ฉันอยากรู้ว่า $data_pemohon เนื่องจาก ->get() จะส่งคืนคอลเล็กชันว่างแทนที่จะเป็น null ในกรณีที่ไม่มีผลลัพธ์ cmiiw   -  person Bagus Tesa    schedule 18.08.2018
comment
หากมีบันทึกอยู่ ? คุณต้องการอัปเดตมันไหม?   -  person Teoman Tıngır    schedule 18.08.2018


คำตอบ (1)


ไม่แน่ใจว่าทำไมคุณถึงใช้ DB Facade แทน Eloquent:

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

หากคุณไม่มี Model สำหรับตาราง antrian_sp หรือเพียงแค่ชอบส่วนหน้าของ DB ก็ควรทำดังนี้:

if ($data_antrian)
person sskoko    schedule 18.08.2018