duanliu8998 2017-03-31 14:54
浏览 25
已采纳

添加从db获取的数字

I collected data from a database and the data is based upon user id, ie I select data from database table based on a user id. Now the selected result has some value (numbers); how do I check if that total sum of the number is equal to a certain amount?

Using Laravel 5.4, I query my db as follows:

 $money = $DBTable::where('id', Auth::user()->id)->get();

Now I have a column called cash how do I get the total sum of the cash column? What is the code for that since the result is an object I do a foreach loop

 foreach ($money as $key => $value) {
     count($money->cash);
 }

this will return the number count of the value:

 foreach ($money as $key => $value) {
     echo $earn->earned_amount + $earn->earned_amount;  
 }

This will add up individual values to themselves, so please can anyone tell me how this is done?

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-03-31 15:21
    关注

    There are two ways to do this:

    1. The Query builder way (https://laravel.com/docs/5.4/queries#aggregates)

      DB::table('table name')->where('user_id', Auth::user()->id) ->sum('cash');

    2. The eloquent way (https://laravel.com/docs/5.4/collections#method-sum)

      Auth::user()->cashTransactions->pluck('cash')->sum('price');

    I assumed you table $DBTable has a model attached to it and that you have a relationship defined between the table's model and the user model

    To define relationship you do:

    in User model:

    public function cashTransactions()
    {
         return $this->hasMany('App\CashTransactions');
    }
    

    in CashTransactions model:

    public function user()
        {
             return $this->belongsTo('App\User');
        }
    

    Edit: you can also define relationships in a model with the same model (self relationship)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?