2 回答
TA贡献1868条经验 获得超4个赞
您最好更改查询,以便仅获取要查找的用户的值。
$amount = DB::table('user_check')->where('user_id', $user)->pluck('amount');
或者如果金额是数组而不是单个值(取决于版本)
$amount = DB::table('user_check')->where('user_id', $user)->value('amount');
或
$user = DB::table('user_check')->where('user_id', $user)->first(); $amount = $user ? $user->amount : 0;
TA贡献1845条经验 获得超8个赞
如果值为“假”、“空”或“0”,则 (int) 将返回 0。我敢打赌,你不希望有这个查询来搜索ID为0的用户,以防请求输入未设置或格式不正确。
让我们清理该代码:
$userId = request()->get('user');
$money = (int) request()->get('money');
# (int) here will be 0 if the request('money') is not sent with the request
# so it makes sense to have it here.
$userCheck = DB::table('user_check')->select('amount')
->where('user_id', $userId)
->first();
# ->first(); if you want to return a single row item
# ->get(); if you want to return multiple items, this one will return a collection (array)
# and you need to treat that accordingly using foreach, or any array function
为什么需要?$array = json_decode(json_encode($data), True);
if($userCheck->amount > $money){
return response(['user ok'=> $userCheck,'money'=>$money]);
}else{
return response('user not ok');
}
现在我假设你正在使用(int)来获取已发送数据的整数值,那里没有实际需要,并且在验证的情况下,你需要单独验证它,如下所示:
如果它在控制器中
$this->validate($request,[
'user'=>'required|exists:user_check,id',
'money'=>'integer'
]);
如果要在其他地方进行验证,您可以:
$validator = Validator::make($request->all(), [
'user'=>'required|exists:user_check,id',
'money'=>'integer'
]);
# Check if it fails
if($validator->fails()){
# Validator fails, stop and return the errors instead
return response()->with($validator->getMessageBag());
}
# This will validate the request and make sure that it has 'user'
# And that 'user' exists in the `user_check` table with that ID
# and that 'money' is an integer
如果您愿意验证,则可以将该代码放在DB::table()...
我希望这能解决你的问题,让我知道它是如何进行的。
- 2 回答
- 0 关注
- 99 浏览
添加回答
举报