我有一个带有事务的客户数据库。
每个事务有两个sql列,借方和贷方。两者都可以填写,也可以只填写一个。
用雄辩的话,我想要的是借方和贷方的总和,这样我就可以得到他的余额。
事务架构如下所示:

Schema::create('transactions', function (Blueprint $table) {
          $table->increments('id');
          $table->datetime('datestamp')->nullable();;
          $table->text('reason')->nullable();;
          $table->decimal('debit')->default(0);
          $table->decimal('credit')->default(0);

          $table->integer('customerId')->unsigned();
          $table->foreign('customerId')->references('id')->on('customers');

          $table->boolean('isDeleted')->default(0);
          $table->timestamps();
      });

我的客户模型如下:
    <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class customer extends Model
{
    public function transaction()
    {
      return $this->hasMany('App\Models\transaction','customerId','id')->where("isDeleted",0)->orderBy('datestamp');
    }

}

我的事务模型如下:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class transaction extends Model
{
    public function balance()
    {
        // problem is that i dont know how to get only for specific customer
        $debit = transaction::sum('debit');
        $credit = transaction::sum('credit');
        return $debit-credit;
    }
}

最佳答案

首先需要一个customer对象,这样就可以通过创建的关系引用它们的事务:

$customer = customer::find(1);

$transactions = $customer->transactions;

$balance = $transactions->sum(function($trans){
    return $trans->debit - $trans->credit;
});

将其放入customer模型很简单:
class customer extends Model
{
    public function transaction()
    {
      return $this->hasMany('App\Models\transaction','customerId','id')->where("isDeleted",0)->orderBy('datestamp');
    }

    public function getBalanceAttribute(){

        return $this->transactions->sum(function($trans){

            return $trans->debit - $trans->credit;

        });
    }
}

现在您可以使用$customer->balance访问客户余额

10-07 23:50