使用laravel eloquent选择特定的字段值。但是,我发现自己正在处理这个错误
SQLSTATE [HY000]:常规错误:1366不正确的整数值:'[{“id”:1}]'用于第1行的'department_id'列(SQL:插入`opportunity`(`category`,`机会) `,`vacancies`,`department_id`,`updated_at`,`created_at`)值(Attachement,Assistant,2,[{“id”:1}],2017-05-04 02:12:04,2017-05 -04 02:12:04))
department_id的字段值应该是int,它从另一个表中绘制,如下所示
public function store(Request $request)
{
// return $request->all();
$this->validate($request,[
'department'=>'required',
'category'=>'required',
'description'=>'required|string',
'positions'=>'required|integer',
]);
//dd($request); table('departments')->where('dep_name', '$dep')
$dep = $request->department;
$department=Department::all();
//dd($department);
$department_id = Department::select('id')->where('dep_name','=', $dep)->get();
// return $department_id;
$newOpportunity = Opportunity::create(
[
'category'=>$request->category,
'opportunity'=>$request->description,
'vacancies'=>$request->positions,
'department_id'=>$department_id,
]
);
$newOpportunity ->save();
return redirect('admin/');
}
答案 0 :(得分:0)
将数组作为值传递给derpartment_id列。 Id位于您需要像这样访问它的数组中
'department_id'=>$department_id[0]->id,
答案 1 :(得分:0)
声明
Department::select('id')->where('dep_name','=', $dep)->get();
返回Collection
。
您需要单个记录的id
。试试这个
$department = Department::where('dep_name','=', $dep)->first();
if($department != null) {
$newOpportunity = Opportunity::create(
[
'category'=>$request->category,
'opportunity'=>$request->description,
'vacancies'=>$request->positions,
'department_id'=>$department->id,
]
);
$newOpportunity ->save();
}
答案 2 :(得分:0)
我认为您需要更新代码,如:
如果单个记录需要id
:
$department_id = Department::where('dep_name','=', $dep)->first();
$newOpportunity = Opportunity::create(
[
'category'=>$request->category,
'opportunity'=>$request->description,
'vacancies'=>$request->positions,
'department_id'=>$department_id->id,
]
);
或者你需要id
多条记录:
$department_id = Department::select('id')->where('dep_name','=', $dep)->get();
foreach($department_id as $department_ids){
$newOpportunity = Opportunity::create(
[
'category'=>$request->category,
'opportunity'=>$request->description,
'vacancies'=>$request->positions,
'department_id'=>$department_ids->id,
]
);
}
希望这会对你有所帮助。
答案 3 :(得分:0)
你真的不需要这个系列。您需要具有一个属性的单个记录 - id
。
您的代码非常脏。尝试避免检索未使用的数据,如下所示:$department=Department::all();
下面的代码从数据库 ONLY ONE 记录中检索,这是正确的方法:
$department = Department::select('id')->where('dep_name','=', $request->department)->first();
完整代码:
public function store(Request $request)
{
$this->validate($request,[
'department' => 'required',
'category' => 'required',
'description' => 'required|string',
'positions' => 'required|integer'
]);
$department = Department::select('id')->where('dep_name','=', $request->department)->first();
if($department) {
$newOpportunity = Opportunity::create([
'category' => $request->category,
'opportunity' => $request->description,
'vacancies' => $request->positions,
'department_id' => $department->id,
]);
$newOpportunity->save();
}
return redirect('admin/');
}