如何使用预先加载在相关模型上获取 SUM,而不加载整个关系数据?
在我的项目中有两个模型,Account和Transaction. 账户模型has many交易。
我的要求是:获取帐户并立即加载相关表上的总和。
提供了我当前的代码:在此代码transactions中预先加载并使用 php 计算总和。但我不想加载整个交易。唯一的要求是sum('amount')。
表:账户
| id | name | address | ...
Run Code Online (Sandbox Code Playgroud)
表:交易
| id | account_id | amount | ...
Run Code Online (Sandbox Code Playgroud)
帐号.php
/**
* Get the transaction records associated with the account.
*/
public function transactions()
{
return $this->hasMany('App\Models\Transaction', 'account_id');
}
Run Code Online (Sandbox Code Playgroud)
以下代码给出了每个账户及其交易。
$account = Account::with(['transactions'])->get();
Run Code Online (Sandbox Code Playgroud)
SUM 使用以下公式计算:
foreach ($accounts as $key => $value) {
echo $value->transactions->sum('amount'). " <br …Run Code Online (Sandbox Code Playgroud) 我有一个角度服务如下所示:
.service('shareDataService', function() {
var myXi = [];
var myYi = [];
var addXi = function(newObj) {
myXi = newObj;
}
var addYi = function(newObj) {
myYi = newObj;
}
var getPlot = function() {
var a = [];
for (var i = 0; i < myXi.length; i++) {
a.push([myXi[i], myYi[i]]);
}
return a;
}
return {
addXi: addXi,
addYi: addYi,
getPlot: getPlot
};
});
Run Code Online (Sandbox Code Playgroud)
我有角度控制器:
.controller('plotController', function($scope, shareDataService) {
$scope.getYo = function() {
return shareDataService.getPlot();
};
$scope.lineChartData = [ …Run Code Online (Sandbox Code Playgroud)