借方余额-雄辩地贷方

时间:2018-07-06 13:48:43

标签: mysql laravel eloquent

我有一个包含交易的客户数据库。 每个事务都有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; 
    }
}

1 个答案:

答案 0 :(得分:1)

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

即可访问客户的余额