我已经搜索了解决方案,但找不到完美解决此问题的方法。 我有以下两种型号
class Payments extends Model
{
protected $table = 'payments';
public function investment_()
{
return $this->belongsTo('App\Investments', 'investment_id', 'id');
}
}
和
class Investments extends Model
{
protected $table = 'investments';
public function payments_()
{
return $this->hasMany('App\Payments', 'investment_id', 'id');
}
}
“付款”具有“金额”列,而投资也具有“金额”列。
如何仅在特定投资的总付款额至少为投资金额的一半的情况下提取所有付款?
我不知道如何构造查询,以便付款可以选择其相应的investment_values并检查条件。
这是我到目前为止在控制器中拥有的
$payments = Payments::where('amount', '>=', Investment::where('id', Payments::where(?)))->get();
注意:我不知道在问号中加什么或我的方法是否正确。
这是一个示例错误查询,可以更好地说明它
SELECT a.SUM(a.amount) AS amount FROM payments as a, investments as b where a.investment_id = b.id and a.sum(a.amount)*2 = b.amount GROUP BY a.investment_id;
答案 0 :(得分:0)
查询只是
SELECT a.SUM(a.amount) AS amount
FROM payments as a JOIN investments as b
ON a.investment_id = b.id
GROUP BY a.investment_id
HAVING SUM(a.amount)*2 < b.amount;
您可以轻松地在Laravel Query构建器元素中翻译thin,但是,如果您只需要此,您可以使用DB::select('query')
来获取它们
答案 1 :(得分:0)
希望这可以解决您的问题。请检查。谢谢
\App\Payment::where(function ($query) {
$query->whereRaw('(select SUM(payment_amount) from payments as payments_final where investment_id = payments.investment_id) >= (select investment_amount/2 from investments where id=payments.investment_id)');
})
->get();