我有两个名为'travel_request'和'status'的表。我有状态值。基于该值我想获取状态表'id'并想要在同一个控制器中更新“travel_request”表status_id。如果我的状态值为'waiting',我想从状态表中取出id = 1并需要将其插入到travel_request表中
状态表-id,状态 travel_request-ID,STATUS_ID
public function statusUpdate(Request $request)
{
$request_data = $request->all();
$id = $request_data['id'];
$status=$request_data['status']; //waiting(1),approved(2),
DB::table('travel_request')
->where('id',$id )
->update(['status_id' => $status]);
return response()->json();
}
答案 0 :(得分:1)
你的意思是这样的:
public function statusUpdate(Request $request)
{
$request_data = $request->all();
$id = $request_data['id'];
$status=$request_data['status']; //waiting(1),approved(2),
DB::table('travel_request')
->where('id',$id )
->update(['status_id' => DB::table('status')->where('COLUMN_NAME', $status)->first()->id]);
return response()->json();
}
答案 1 :(得分:1)
使用Eloquent:
public function statusUpdate(Request $request)
{
$status_id = Status::where('status', $request->status)->first()->id;
TravelRequest::where('id', $request->id)->update(compact('status_id'));
return response()->json();
}
另一种方法是在配置文件中保留状态,例如:
status => [
'waiting' => 1,
'approved' => 2,
],
然后代码看起来像这样:
public function statusUpdate(Request $request)
{
TravelRequest::where('id', $request->id)
->update(['status_id' => config('conf.status')[$request->status]]);
return response()->json();
}
答案 2 :(得分:0)
public function statusUpdate(Request $request)
{
$id = $request->id; //get the id
$request['status_id'] = $request->status; //get the status value on status_id
DB::table('travel_request')
->where('id',$id )
->update(only(['status_id'])); //update only status_id field
return response()->json();
}