gpt4 book ai didi

php - Laravel : Check if record exists Before Insertion

转载 作者:行者123 更新时间:2023-12-03 08:48:27 34 4
gpt4 key购买 nike

我有两张 table : assignments 表(列 assignment_idStaff Nameasset_iddepartmentdatestatus )和 assets 表(列 asset_idtag_nameserial_numbermodel_numbercolor )。 Assets 表列与 链接作业 table 。我想插入到分配表中,但在插入之前,我想检查 asset_id 已存在于分配表中,如果是 status = 'Active' 那么插入应该抛出错误/不应该发生。

作业 Controller

class AssignmentController extends Controller
{

public function assignment(){
$assignments = Assignment::all();
return view('assignment/index', ['assignments' => $assignments]);
}

public function add(Request $request){

$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignments = new Assignment;
$assignments ->assignment_id = $request->input('assignment_id');
$assignments ->staff_id = $request->input('staff_id');
$assignments ->asset_id = $request->input('asset_id');
$assignments ->department_id = $request->input('department_id');
$assignments ->date = $request->input('date');
$assignments ->status = $request->input('status');

$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}

$assignments ->save();
return redirect('/assignment/index') ->with('info', 'New Assignment Saved Successfully!');
}

Assginment.php
class Assignment extends Model
{
protected $primaryKey = 'assignment_id';

public function asset()
{
return $this->belongsTo('App\Asset', 'asset_id');
}
}

以下变量和 中的 if 语句AssignmentsController 总是在 中抛出错误if statement 无论它是否正确并且插入不会发生,但是当整个语句被清除时,插入就会发生。
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}

所以我想要一种方法来检查要插入的记录是否已经存在,条件好像 asset_id 存在然后检查它的 status 如果它是 ='Active' 然后抛出一个错误,但如果不是,则插入发生。如果你明白,请帮助。提前致谢。

最佳答案

你可以这样做:

public function add(Request $request){
$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignment = Assignment::firstOrNew([
"status" => "Active",
"asset_id" => $assignments->asset_id
], $request->all());
abort_if($assignment->exists(), 405, 'Trying to assign an already assigned asset');
$assignment->save();
return redirect('/assignment/index')
->with('info', 'New Assignment Saved Successfully!');
}

关于php - Laravel : Check if record exists Before Insertion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710470/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com