如何在Fluent查询中加入和过滤聚合并保留json结构?

时间:2015-03-03 18:50:44

标签: php json laravel aggregate fluent

我一直试图让我的模型与Laravel(4.2)中的聚合语句很好地配合,但无济于事。当我使用'join'时,嵌套的json结构会清空其记录。它基于贷款和支付。 这是一个简化的架构:

付款:id | loan_id |付款|预期 贷款:id | collectiontype_id | principal_amount

我需要查看一个帐户是否有欠款,多少以及显示过去的付款。

以下是模型:

Loan.php

public function payment()
{
    return $this->hasMany('Payment');
}

Payment.php

public function loan()
{
    return $this->belongsTo('Loan');
}

执行以下操作可以获得付款所需的所有数据:

Loan::with('collectiontype','payment')->get(); 

有一次,我在贷款模型中有以下内容:

public function payAggregate()
{

    return $this->hasOne('Payaggregate','loan_id','id')
                ->select(DB::raw("loan_id, count(*) as count, sum(expected) as sumexpected, sum(paid) as sumpaid, (sum(expected) - sum(paid)) as arrears"))
                ->groupBy('loan_id')
                ->having('arrears','>',10); 
}

这在隔离方面运作良好。但是,当我尝试做'with'时:

Loan::with('collectiontype','payment','payaggregate')->get(); 

它没有有条款,但没有。我试过'has','whereHas'和许多奇怪而美妙的东西,但它们似乎都不适合我。

然后我考虑使用连接手动创建:

$v= DB::table('loans AS l')
    ->select(array('l.*', 'p.arrears','ct.shortlabel','pay.paid', 'pay.expected'))
    ->join(DB::raw('(SELECT loan_id, count(*) as count, sum(expected) as sumexpected, sum(paid) as sumpaid, (sum(expected) - sum(paid)) as arrears FROM payments GROUP BY loan_id) AS p'), function( $query ){
        $query->on( 'l.id', '=', 'p.loan_id' );
                    })
    ->join(DB::raw('(SELECT * FROM collectiontypes) AS ct'), function( $query ){
        $query->on( 'l.actualcollection', '=', 'ct.id' );
    })
    ->join(DB::raw('(SELECT * FROM payments) AS pay'), function( $query ){
        $query->on( 'l.id', '=', 'pay.loan_id' );
    })  
    ->where('p.arrears', '>', 10)->paginate(30);

$v->getCollection()->toJson();

然而,这只是在没有嵌套付款对象的情况下提供了平坦的输出。我希望我能清楚地阐明这个问题。

0 个答案:

没有答案