【发布时间】:2021-07-24 08:22:37
【问题描述】:
我有一个表用户和表支付,它们使用一对多关系相互连接, 在我的用户表中,我有一个列名 client_type,其值为 {住宅、商业、医疗和工业),如果此 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;
});
我的输出 错误异常 试图获得非对象的财产“付款”
如何解决这个问题,提前谢谢,
【问题讨论】:
标签: laravel eloquent-relationship