【问题标题】:how to check if data already exist when insert data插入数据时如何检查数据是否已经存在
【发布时间】:2020-01-21 15:03:34
【问题描述】:

我想问如果有相同的数据不能插入,我们输入数据时如何检查数据。

我的代码:

$obj = new Pengajuan();
//   $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
    $status = "Tersmpan";
} else {
    $status = "Gagal";
}
echo json_encode(array("status" => $status));

【问题讨论】:

标签: php laravel


【解决方案1】:

试试这个:

public function store(Request $request)
{
    $this->validate($request,[
        'id_nasabah'=>'required|exists:your_table_name,id',
        'tgl_pengajuan'=>'more_validations',
        'besar_pinjaman'=>'more_validations',
    ]);

    //if $this->validate() fails, it will return a response 422 code error
    //else it will continue with the creation of your object 

    //is a good idea to use a try-catch in case of something goes wrong
    try
    {
        $pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));

        return response->json([
            'pengajuan'=>$pengajuan,
            'status'=>'Tersmpan',
        ],200);//return a http code 200 ok
    }
    catch(Exception $e)
    {
        //'message'=>'this will return what is the error and line'
        return response()->json([
            'message'=>$e->getMessage().'/'.$e->getLine(),
            'status'=>'Gagal',
        ],422);
    }
}

【讨论】:

    【解决方案2】:

    在代码上方添加如下验证:

     $this->validate([
    'id_nasabah' =>'unique:pengajuans'
    ]) ;
    

    然后是其余的控制器代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 2020-02-04
      • 2015-07-12
      • 1970-01-01
      • 2021-06-13
      • 2020-07-15
      • 1970-01-01
      • 2019-02-05
      相关资源
      最近更新 更多