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

h5qlskok  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(236)

我有一个来自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);
}

我搜索了一些堆栈溢出页面。通过身份证找到了存在,这是样本,

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

但我想比较一下日期和地点。如果它们不存在,我想让用户保存它。基本上是试图阻止重复条目。
请帮帮我。

wd2eg0qa

wd2eg0qa1#

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

$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 属性,以确保没有具有相同数据和位置的成员。

yrwegjxp

yrwegjxp2#

有很多很好的帮助函数 firstOrNew 以及 firstOrCreate ,后者将直接创建它,而第一个需要显式调用 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
iyfamqjs

iyfamqjs3#

最好的方法是对多个列使用laravel惟一验证。看看这个。我是这么想的 id 是你的主键,在 sampling_orders table。验证规则如下所示:

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

p、 s:我没有看到 place 在您的 StoreSampling()

相关问题