借方余额-贷方余额

agyaoht7  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(620)

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

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; 
    }
}
i1icjdpr

i1icjdpr1#

你首先需要一个 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

相关问题