获取另一个 table 的值并求和

Getting the value of another table and summing it up

我有一个 table 用户和 table 付款,它们使用一对多关系相互连接, 在我的用户 table 中,我有一个列名 client_type ,其值是 {residential, commercial, medical and industrial),如果任何此 clientType 进行付款,他的 user_id 将存储在付款中连同支付的金额..现在,我想从我的 payment_table 中计算任何此 clientType 支付的所有金额。

下面是我的代码 用户模型

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'address',
        'phone',
        'email',
        'lga',
        'ogwema_ref',
        'password',
        'role',
        'client_type'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }
}

// Payment Model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'user_id',
        'amount',
        'bank_charges',
        'ref',
        'paystack_ref',
        'status',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
This is the code am trying to solve it
Route::get('/chart', function () {
    $residential = DB::select('select id from users where client_type = ?', ['residential']);
    return $residential->payments;
    
    
});

我的输出 错误异常 尝试获取 属性 'payments' 的非对象

我该如何解决这个问题,在此先感谢,

你得到这个错误是因为你写了一个本地查询所以它没有访问 eloquent 模型所以要修复你可以通过 eloquent query

来写它
$residential = User::where('client_type', 'residential')->with('payments')->get();

如果您想获得每个用户的总付款,您只需添加 withSum 方法

$residential = User::where('client_type', 'residential')->withSum('payments', 'amount')->get();

此 select 命令 $residential = DB::select('select id from users where client_type = ?', ['residential']); returns 结果数组(不是对象)因此此行 $residential->payments 抛出 ErrorException.

select命令的逻辑应该是这样的:

$totalMoney = DB::select('select sum(amount) from users INNER JOIN payments ON users.id=payments.user_id where users.client_type = ?', ['residential']);