数据插入之前对数据库数据字段的检查

时间:2018-11-21 14:29:55

标签: php mysql database laravel laravel-5

我有一个来自HTML页面的数据。我想检查日期和地方值是否已经存在。如果它们存在,它应该抛出一个错误,说数据已经存在,如果那些日期和地点数据不存在,则应该允许用户保存它。

这是我为保存而编写的代码,

public function StoreSampling(Request $request)
{
  $date = Carbon::createFromFormat('d-m-Y', $request->input('date'))->format('Y-m-d');

  $doctorname = Input::get('doctorselected');
  $product = Input::get('product');
  $product= implode(',', $product);
  $quantity = Input::get('qty');
  $quantity =implode(',',$quantity);
  $representativeid = Input::get('representativeid');
  //Store all the parameters.
  $samplingOrder = new   SamplingOrder();
  $samplingOrder->date = $date;
  $samplingOrder->doctorselected = $doctorname;
  $samplingOrder->products = $product;
  $samplingOrder->quantity = $quantity;
  $samplingOrder->representativeid = $representativeid;
  $samplingOrder->save();
  return redirect()->back()->with('success',true);
}

我在流程页面上搜索了一些Stack。并通过ID找到了存在的内容。这是示例

$count = DB::table('teammembersall')
    ->where('TeamId', $teamNameSelectBoxInTeamMembers)
    ->where('UserId', $userNameSelectBoxInTeamMembers)
    ->count();

if ($count > 0){
    // This user already in a team
    //send error message
} else {
    DB::table('teammembersall')->insert($data);
}

但是我想比较日期和地点。如果它们不存在,我想让用户保存它。基本上是尝试停止重复的条目。

请帮助我。

3 个答案:

答案 0 :(得分:1)

对此有非常好的帮助函数,分别称为firstOrNewfirstOrCreate,后者将直接创建它,而第一个则需要显式调用save。因此,我将遵循以下条件:

$order = SamplingOrder::firstOrNew([
  'date' => $date,
  'place' => $place 
], [
   'doctorname'       => Input::get('doctorselected'),
   'product'          => implode(',', Input::get('product')),
   'quantity'         => implode(',',Input::get('qty')),
   'representativeid' => Input::get('representativeid')
]);

if($order->exists()) {
   // throw error
   return;
}

$order->save();
// success

答案 1 :(得分:0)

您需要将查询修改为以下内容:

$userAlreadyInTeam = SamplingOrder::where('date', $date)
    ->where('place', $place) // I'm not sure what the attribute name is for this as not mentioned in question
    // any other conditions
    ->exists();

if (userAlreadyInTeam) {
    // Handle error
} else {
    // Create
}

您无需使用count()作为确定存在的唯一方法。

还可以考虑向数据库添加多列unique属性,以确保没有相同数据和位置的成员。

答案 2 :(得分:0)

最好的方法是在多列上使用laravel unique validation。看一下this。 我假设id是您的主键,并且在sampling_orders表中。验证规则如下:

'date' => ['unique:sampling_orders,date,'.$date.',NULL,id,place,'.$place]

p.s:在您的place中看不到任何StoreSampling()输入