检查Laravel 5.5中是否存在记录

时间:2017-12-19 03:06:31

标签: php laravel

我有一个动态输入表单,我想检查记录是否存在,如果没有则不能插入数据

我的控制器

$user = Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->get();

   if($user->isEmpty()){
      // insert
   }else{
     //message "cannot input"
   }

如果插入一个数据,成功..但如果插入数组在我的控制器中没有检查.. 为什么在输入数组数据中总是插入???

3 个答案:

答案 0 :(得分:1)

这只是伪检查id_b

   $data = [1,2,3,4];
   $data_a = [1,2,3,4];

    $masters = Master::whereIn('id_b', $data)->whereIn('id_a', $data_a)->get();

    foreach($data as $key => $value) {
        $isExisted = false;

        foreach ($masters as $master) {
            if ($master->id_b == $value[$key] && $master->id_a == $data_a[$key])
            {
                $isExisted = true;
                break;
            }
        }

        if ( ! $isExisted) {
            $master = new Banner();
            $master->value = your_data;
            $master->save();
        }
    }

答案 1 :(得分:0)

您可以使用exists()

if __name__== '__main__':
    AvailableNetworks()
    BroadcastAddy()

    # This combines lists so 
    FinalReport = zip(GoodNets, BroadcastAddresses)
    # zip() creates immutable tuples that will give you hell if you try to run them through .format()
    # So I convert FinalReport back into list of lists
    FinalReport = [list(elem) for elem in FinalReport]
    # Bug check (Delete this before final)
    print("this is the type of final report:", type(FinalReport))
    # Bug check, print the FinalReport to see what inside. 
    print(FinalReport)
    # Formatted, when combined with .format() will create 2 columns. I've printed to column titles
    # to prove this works. 
    formatted = "{:^30}{:^30}"
    print(formatted.format("Network Addresses", "Broadcast Addresses"))
    # Now, I try to print FinalReport in 2 columns. 
    for list in FinalReport:
        for num in list:
            print(formatted.format(num, num))
            break

另外我建议你减少你正在做的在线内容,而不是像这样:

if(Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->exists()) {
do something
}

答案 2 :(得分:0)

如果我理解正确,如果某个 <已经存在给定的Masterid_a,则需要插入id_b < / p>

如果是这样,您实际上可以使用firstOrCreate

Master::firstOrCreate(
  ['id_a' => $request->get('id_a'), 'id_b' => $request->get('id_b')], 
  ['yourcolumntocreate' => columnvalue, ...]
)