即使没有行也从数据库中获取最新值

时间:2019-03-21 04:16:28

标签: php laravel

因此,我试图通过获取总积分并将其与安装点相加的方式来获取积分表,以供用户添加积分,但是,通过尝试获取其“最新”积分,新用户将没有积分表中的现有行将抛出错误“ InvalidArgumentException; Data Missing” 。这将是下面的代码,并且还有其他解决方法吗?

$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
        $points['user_id'] = $input['user_id'];
        $points['points_add'] = $battery['point_installation'];
        $points['points_subtract'] = 0;
        $points['points_total'] = $currentpoint + $battery['point_installation'];
        $points['points_source_id'] = 1;
        $points['created_at'] = $mytime;
        $points['updated_at'] = $mytime;
$point = Points::create($points);

1 个答案:

答案 0 :(得分:0)

代码的

$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();返回一个对象,并且您试图对该对象执行数学(加法)运算,而这是不可能的。您可以像下面那样更新代码。

$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();

        $points['user_id'] = $input['user_id'];
        $points['points_add'] = $battery['point_installation'];
        $points['points_subtract'] = 0;
        if($currentpoint != null)
        {
         $points['points_total'] = $currentpoint->points_total + $battery['point_installation'];
        }
        else {
          $points['points_total'] = $battery['point_installation'];
         }

        $points['points_source_id'] = 1;
        $points['created_at'] = $mytime;
        $points['updated_at'] = $mytime;
$point = Points::create($points);