简体   繁体   English

Laravel function 取 Model id vs function 取 Model 本身

[英]Laravel function take Model id vs function take Model itself

I want to know what should be the best approach to make function:我想知道制作 function 的最佳方法是什么:

function get_total_payment($payment_id){
   return PaymentModel::where('payment_id', $payment_id )->sum('amount');
}

function get_total_payment($payments){
    return $payments->sum('amount');
}

what I think is the second approch is save us when refactoring code.我认为第二种方法是在重构代码时拯救我们。

both work but I want to know the pros and cons两者都有效,但我想知道优缺点

In my opinion, I think it's better to use eloquent scopes to make the total work on many different situations.在我看来,我认为最好使用 eloquent 范围来使总计适用于许多不同的情况。 see the examples below:请参阅以下示例:

function scopeGetTotalPayment($query){
     $query->sum('amount')
}

now you can Implement it for different situations.现在您可以针对不同的情况实施它。 see the examples below:请参阅以下示例:

//get the total amount of payments for the whole payments in the table
$totalPayment = PaymentModel::getTotalPayment();

//get the total payments for a specific user 
$totalPayment = PaymentModel::where('user_id', $userId)->getTotalPayment();
 

In the end, it depends on you.最后,这取决于你。 you can either use the scopes or stick with the normal sum.您可以使用示波器或坚持使用正常总和。 I think that the added value of using the scope in your case is only for making the name clear and to make it work for a specific column.我认为在您的案例中使用 scope 的附加值只是为了使名称清晰并使其适用于特定列。

read more about eloquent scopes: https://laravel.com/docs/9.x/eloquent#query-scopes阅读更多关于 eloquent 范围的信息: https://laravel.com/docs/9.x/eloquent#query-scopes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM