【发布时间】:2018-12-16 00:12:04
【问题描述】:
在我的数据库中我有instagram_actions_histories 表,其中我有action_type 列,在列中我有不同的数据,例如1 或2 或3
我正在尝试在关系中获取此表数据并将存储在列中的这些值相加,例如
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select(['action_type as count'])->whereActionType(1)->sum('action_type');
}
]
)->get();
顺便说一句,此代码不正确,因为我想在其中获取所有 history 和多个 sum
whereActionType(1)->sum('action_type')
whereActionType(2)->sum('action_type')
whereActionType(3)->sum('action_type')
例如(伪代码):
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select(['action_type as like'])->whereActionType(1)->sum('action_type');
$query->select(['action_type as follow'])->whereActionType(2)->sum('action_type');
$query->select(['action_type as unfollow'])->whereActionType(3)->sum('action_type');
}
]
)->get();
更新:
$userAddedPagesList = auth()->user()->instagramPages()->with([
'history' => function ($query) {
$query->select('*')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '1');
}, 'like')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '2');
}, 'follow')
->selectSub(function ($query) {
return $query->selectRaw('SUM(action_type)')
->where('action_type', '=', '3');
}, 'followBack');
}
]
)->get();
错误:
Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select *, (select SUM(action_type) where `action_type` = 1) as `like`, (select SUM(action_type) where `action_type` = 2) as `follow`, (select SUM(action_type) where `action_type` = 3) as `followBack` from `instagram_actions_histories` where `instagram_actions_histories`.`account_id` in (1, 2, 3))
我该如何实施这个解决方案?
更新:
InstagramAccount 类:
class InstagramAccount extends Model
{
...
public function schedule()
{
return $this->hasOne(ScheduleInstagramAccounts::class, 'account_id');
}
public function history()
{
return $this->hasMany(InstagramActionsHistory::class, 'account_id');
}
}
InstagramActionsHistory 类:
class InstagramActionsHistory extends Model
{
protected $guarded=['id'];
public function page(){
return $this->belongsTo(InstagramAccount::class);
}
}
用户类别:
class User extends Authenticatable
{
use Notifiable;
...
public function instagramPages()
{
return $this->hasMany(InstagramAccount::class);
}
}
【问题讨论】:
-
是您需要的原始查询,例如: select action_type, count(*) from your table group by action_type ?
-
@koalaok 我需要求和 action_type 时为 1,求和 action_type 时为 2,然后求和 action_type 时为 3
-
也许我错过了一些额外的信息……但这对我来说越来越奇怪了。看起来你想对所有具有相同值的记录求和......通常它是一个计数......或者如果你真的需要 count()*value 的总和然后使用 SUM(): SELECT action_type, SUM( action_type) FROM instagram_actions_histories GROUP BY action_type
-
Laravel 是对的,您将聚合子查询
selectSub()与普通缩放器结果select('*')混合在一起。您是否想要每个用户的结果以及各自的 SUM? -
@Viney 如果我理解你的意思,对于每张有内部关系的桌子,每张
action_type的总和更多@
标签: php laravel laravel-5.6