逻辑:用户有很多信用。
控制器:
public function getAdminAccount()
{
$company = User::find(Auth::user()->id)
->companies()
->with('users.credits')
->first();
$this->layout->content = View::make('agents.admin.account',
array('company' => $company));
}
我的控制器功能正在返回我需要的JSON数据中的正确数据,但是,我希望按照user_id
计算结果,最好在它们在视图中显示之前。
JSON:
[
{
"id":"4",
"user_id":"4",
"credits":"10",
"created_at":"2013-09-30 09:39:25",
"updated_at":"0000-00-00 00:00:00"
},
{
"id":"67",
"user_id":"4",
"credits":"6",
"created_at":"2013-08-05 12:40:25",
"updated_at":"0000-00-00 00:00:00"
}
][
{
"id":"6",
"user_id":"6",
"credits":"9",
"created_at":"2013-06-25 16:24:18",
"updated_at":"0000-00-00 00:00:00"
},
{
"id":"69",
"user_id":"6",
"credits":"2",
"created_at":"2014-01-16 10:09:55",
"updated_at":"0000-00-00 00:00:00"
}
]]
所以,对于那个JSON结果,应该说:
据我所知,在控制器中格式化JSON是有益的,而不是视图。我尝试了->sum()
,->groupBy()
功能,但没有成功。
谢谢。
更新
public function getAdminAccount()
{
$company = User::find(Auth::user()->id)
->companies()
->with('users.credits')
->get()
->sum('credits');
$this->layout->content = View::make('agents.admin.account', array('company' => $company));
}
以上功能将积分总数加在一起,非常接近我所需要的!我只需要构成总数的每个用户的积分数量!
更新
使用此forloop似乎返回正确的MYSQL逻辑,但仍然没有正确的值:
@foreach ($company->users as $user)
{{ $user->credits()->count('credits') }}<br>
@endforeach
MYSQL:
select count(`credits`) as aggregate from `usages` where `usages`.`user_id` = '4'
答案 0 :(得分:1)
您需要的是sum
而非count
,但无论如何在循环中使用它意味着n + 1问题,因此您最好这样做:
// User model
public function creditsSum()
{
return $this->hasOne('Credit')
->selectRaw('user_id, sum(credits) as sum') // user_id must be in select to match the models
->addSelect(DB::raw('count(*) as count')) // that just in case you also need
// credits count, if not remove
->groupBy('category_id');
}
// Then you can access it as easily as every relation:
User::with('creditsSum')->get();
// you will have eager loaded data on each user model:
$user->credits_sum->sum;
$user->credits_sum->count; // if you select it too
答案 1 :(得分:0)
如果我以正确的方式预测您的数据库布局,我认为连接是最快的解决方案。这样您就不需要为每个用户触发查询。它也是SUM
而不是COUNT
,count只计算数据集的数量。
$company->users()->join('credits', 'users.id', '=', 'credits.user_id')
->selectRaw('SUM(credits.credits) as `total_credits`, users.username')
->groupBy('credits.user_id')->get();
这应该给你类似
的东西total_credits | username
------------------------
24 | John
12 | Michael
如果您还希望获得没有任何积分的用户,则应使用leftJoin
。