如何使用Laravel查询构建器合并这两个函数

时间:2018-06-25 10:36:30

标签: php laravel

我需要在计算完一个成员的所有应收款和应收款之后导出最终金额,我在两个函数中做了如何将它们合并的操作

public function memberReceivable($id){

    return $this->join('transactions', 'transactions.id', '=', 'member_transactions.transaction_id')
    ->leftjoin('accounts', 'accounts.id', '=', 'transactions.account_id')
    ->selectRaw("transactions.unit as currency,sum(transactions.amount) as amount")
    ->where('accounts.type','accountsReceivable')
    ->where('member_transactions.member_id',$id)
    ->groupBy('transactions.unit')->get();    
}

public function memberPayable($id){

    return $this->join('transactions', 'transactions.id', '=', 'member_transactions.transaction_id')
             ->leftjoin('accounts', 'accounts.id', '=', 'transactions.account_id')
             ->selectRaw("transactions.unit as currency,sum(transactions.amount) as amount")
             ->where('accounts.type','accountsPayable')
             ->where('member_transactions.member_id',$id)
             ->groupBy('transactions.unit')->get();
}

1 个答案:

答案 0 :(得分:1)

public function member($id = null, $type = ""){
    $response = $this->join('transactions', 'transactions.id', '=', 
    'member_transactions.transaction_id')
    ->leftjoin('accounts', 'accounts.id', '=', 'transactions.account_id')
    ->selectRaw("transactions.unit as currency,sum(transactions.amount) as amount");

    if($type){
      $response->where('accounts.type', $type);
    }

    if($id){
      $response->where('member_transactions.member_id',$id);
    }

    $response->groupBy('transactions.unit')->get();

    return $response;
}

您可以尝试。