【发布时间】:2019-03-14 21:22:50
【问题描述】:
我想将此 SQL 查询转换为 laravel eloquent 查询。所以我可以创建
SELECT
count(distinct article_id) as assigned
FROM
actions
WHERE
action_id = 1 and
set_id = 1
我可以将查询转换为有效的原始请求
DB::table('actions')->select(DB::raw('count(DISTINCT article_id) as assigned'))
->where('action_id', 1)
->where('set_id', 1)
->get();
但我想弄清楚如何做这样的事情
$sets = Set::withCount(['actions as assigned' => function ($q) {
$q->distinct()
->select('article_id')
->where('action_id', '=', 1);
}])->get();
或者这个
$sets = Set::withCount(['actions as assigned' => function ($q) {
$q->distinct('article_id')
->where('action_id', '=', 1);
}])->get();
最终我想让我的 Set 模型包含一个像这样的作用域方法
public function scopeWithAssignedCount($query){
$query->withCount(['actions as assigned' => function ($q) {
$q->distinct('article_id')
->where('action_id', '=', 1);
}])
}
所以我可以在我的控制器中为单个调用添加多个计数
$sets = Set::withAssignedCount()
->withUnassignedCount()
->where('palm' => $face)
->get();
按 cmets 编辑
我想使用如下所示的不同记录。
public function scopeWithAssignedCount($query)
{
$query->withCount(['actions as assigned' => function ($q) {
$q->where('action_id', 1);
}]);
}
【问题讨论】:
-
最后一个查询 (
Set::withAssignedCount()->[...]) 应该生成什么 SQL? -
同初始查询。我想将 sql 查询与其他人链接起来。
-
它们完全不同,最后一个查询从 sets 表中选择。
-
我以前做过这个,没有区别,效果很好。我将编辑我的问题。