Laravel 5 中使用查询生成器的复杂查询
Posted
技术标签:
【中文标题】Laravel 5 中使用查询生成器的复杂查询【英文标题】:Complex query with query builder in Laravel 5 【发布时间】:2015-12-21 16:30:23 【问题描述】:我有 3 张桌子,
subscribers
:
subscribers_lists_subscribers
:
还有subscribers_lists
:
我正在尝试这样的查询:
$baseQuery = DB::table('subscribers_lists')
->leftjoin('subscribers_lists_subscribers', 'subscribers_lists.id', '=', 'subscribers_lists_subscribers.subscribers_list_id')
->leftjoin('subscribers', 'subscribers_lists_subscribers.subscriber_id', '=', 'subscribers.id')
->select(
'subscribers_lists.id as count_clickers',
DB::raw('count(subscribers_lists_subscribers.subscribers_list_id where subscribers.status = "Active") as count_active')
'subscribers_lists.updated_at as last_activity'
)
->groupBy('subscribers_lists.id');
我需要这个:
where subscribers.status = "Active"
我遇到了一个错误,谁能告诉我我做错了什么?
【问题讨论】:
您不能只为一个字段使用where
。正确的语法是将where
放在select
之后和groupBy
之前。
那么,我该怎么做呢,请帮忙
错误信息是什么?
您应该考虑将这些屏幕截图替换为文本等价物。
【参考方案1】:
您在其中一个选择之后缺少一个逗号,并且您不能简单地在选择语句中放置诸如“where subscribers.status = "Active"”之类的内容。试试这个:
$baseQuery = DB::table( 'subscribers_lists')
->leftJoin('subscribers_lists_subscribers', 'subscribers_lists.id', '=', 'subscribers_lists_subscribers.subscribers_list_id')
->leftJoin('subscribers', 'subscribers_lists_subscribers.subscriber_id', '=', 'subscribers.id')
->select(
'subscribers_lists.id as count_clickers',
DB::raw('COUNT(subscribers_lists_subscribers.subscribers_list_id) as count_active'),
'subscribers_lists.updated_at as last_activity'
)
->where('subscribers.status', 'Active')
->groupBy('subscribers_lists.id');
【讨论】:
【参考方案2】:我做到了,
$baseQuery = DB::table( 'subscribers_lists')
->leftjoin('subscribers_lists_subscribers', 'subscribers_lists.id', '=', 'subscribers_lists_subscribers.subscribers_list_id')
->leftjoin('subscribers', 'subscribers_lists_subscribers.subscriber_id', '=', 'subscribers.id')
->select(
'subscribers_lists.id',
'subscribers_lists.name',
'subscribers_lists.id as count_openers',
'subscribers_lists.id as count_clickers',
DB::raw('count(case when subscribers.status = "Active" then 1 else null end) as count_active'),
DB::raw('count(case when subscribers.status = "Unsubsribed" then 1 else null end) as count_unsubsribers'),
DB::raw('count(case when subscribers.status = "Bounced" then 1 else null end) as count_bounced'),
DB::raw('count(subscribers_lists_subscribers.subscribers_list_id) as count_total'),
'subscribers_lists.updated_at as last_activity'
)
->where('subscribers_lists.user_id', '=', $user_ID)
->groupBy('subscribers_lists.id');
$totalData = $baseQuery->count();
【讨论】:
以上是关于Laravel 5 中使用查询生成器的复杂查询的主要内容,如果未能解决你的问题,请参考以下文章