我试图在laravel-5.4上构建一个小型应用程序,其中我有一个关系查询,如下所示:
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get();现在,我想收集从查询中生成的所有contact_association_counts,并将其添加到单独的公司集合中--为此,我使用了pluck、collapse和sum方法,但我不知道它不是按需要计算的。以下是截图:
我得到的收藏清单如下:

现在我得到了以下属性:

现在是关系数据:

现在,交互数据,其中计数属于:

为此,我试了一下:
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get()
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
->collapse()
->sum();
return $company;
});但是这不是计算计数,所有的计数都是0。
帮我解决这个问题。谢谢
发布于 2017-09-22 03:35:39
我相信您的问题是->collapse(),在->pluck('interaction.contacts_association_count')之后看到您的示例,您应该有一个平面数组作为[1,2,3,4,5],如果将collapse()应用于平面数组,它将返回一个空数组[],并且一个空数组的和为0。
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get()
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
//->collapse()
->sum();
return $company;
});我希望能成功..。祝好运!
https://stackoverflow.com/questions/46356250
复制相似问题