Laravel连接表和总金额

时间:2020-08-14 08:29:37

标签: jquery laravel

我有2个表,例如用户表和交易表。

Users
id | name
1  | name1
2  | name2
3  | name3

Transactions
id | amount | send_id | receive_id
1  |   10   |    1    |     2
2  |   20   |    1    |     2
3  |   15   |    2    |     3
4  |   32   |    3    |     1

我想从每个用户的交易中获取金额。该数量应为接收总数-例如name1的发送为32(receive)-30(send)= 2。

类似

[{id:1, name: 'name1', total: 2}, {id:2, name: 'name2', total: 15}, {id:3, name: 'name3', total: 15}]

这是我尝试的代码,但出现max_join_size错误。

$users= DB::table("users")
      ->selectRaw('users.*, sum(transactions.amount) As total')
      ->join('transactions', 'users.id', '=', 'transactions.receive_id')
      ->join('transactions as t1', 'users.id', '=', 't1.send_id')
      ->groupBy('users.id')
      ->orderBy('total', 'DESC')
      ->paginate(10);

我想按总数进行分页和排序,而无需致电所有用户。 如果有人知道更好的方法,请提供帮助。

1 个答案:

答案 0 :(得分:0)

ORM解决方案

仅当您有用于表的模型并且要使用口才的ORM时,我才建议此解决方案,在User模型中,我们将为sent和{{1}添加两个关系}交易,然后我们将附加一个received属性以进行计算(接收-发送),因此在您的total模型中,您将添加

User

现在无论您在哪里吸引用户

protected $appends = ['total'];

public function sent()
{
   return $this->hasMany(Transaction::class, 'send_id');
}

public function received()
{
   return $this->hasMany(Transaction::class, 'receive_id');
}

public function getTotalAttribute()
{
   return $this->received()->sum('amount') - $this->sent()->sum('amount');
}

现在您可以$users = User::query()->get()->map(function (User $user) { return [ 'id' => $user->id, 'name' => $user->name, 'total' => $user->total, ]; }); 查看结果

另一种解决方案

我们将在dd($users);模型中添加一个函数,而不是使用附加函数来像这样计算(接收-发送)

User

现在要获得public function sent() { return $this->hasMany(Transaction::class, 'send_id'); } public function received() { return $this->hasMany(Transaction::class, 'receive_id'); } public function total() { return $this->received()->sum('amount') - $this->sent()->sum('amount'); } ,您会做

total()