【问题标题】:Return count on an eager-loaded relation Laravel返回快速加载关系 Laravel 的计数
【发布时间】:2018-03-12 19:24:31
【问题描述】:

所以我有包含StackSubject,其中包含Question。每个问题都有答案,我想统计每个Stack的答案,但我卡住了。

这是我正在尝试做的,我一直在摆弄的众多解决方案之一:

    $subjects = Subject::with(['stack.question', 'stack.answersCount'])->get();

    return $subjects;

Subject 模型有如下关系:

public function stack(){
    return $this->hasMany(Stack::class);
}

如果我们看一下Stack 模型中的关系是如何建立的:

public function question(){
    return $this->hasMany(Question::class);
}

public function answers(){
    return $this->hasMany(Answers::class);
}

public function answersCount(){
    return $this->answers()->selectRaw('answer, count(*) as aggregate')->groupBy('answer');
}

但是当我return $subjects时,answer_count是空的。

"answers_count": []

这很令人困惑,因为当我在 SQL 中运行相同的查询时,我得到非空结果。

select answer, count(*) as aggregate from `answers` where `answers`.`stack_id` in ('1', '6') group by `answer`

correct 9
wrong   4

那么我如何计算所有答案呢?并将它们分组?

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    删除 answersCount 关系 - 不再需要,因为您可以使用 withCount 方法:

    $subjects = Subject::with([
        'stack.question', 
        'stack' => function ($q) {
            $q->withCount('answers');
        }
    ])->get();
    
    // then on each subject you can call stack->answers_count
    $subjects->first()->stack->answers_count
    

    【讨论】:

    • 是的,这是一个很好的解决方案,但不幸的是,我想将计数分组到 correctwrong
    • 所以创建 2 个适当的关系,如果它们都调用 withCount
    • 这就是我目前所做的,我在堆栈模型上有wrongAnswer()correctAnswer()。如果我想获取特定用户,我可以拨打withCount() 甚至附加where
    【解决方案2】:

    试试这个方法

    $subjects = Subject::with(['stack.question', 'stack.answersCount'])->get();
    $count = $subjects->answersCount->first()->aggregate;
    
    //count varible will have the count now you can use it as you would like to 
    
    return $subjects;
    

    进一步挖掘可以找到here

    【讨论】:

    • 这似乎是一种替代方案,但是否可以按照我描述的方式获取计数?这似乎是一种非常干净的方法。而且我也不明白为什么它也不起作用。
    • 我需要调查一下,我猜你试过了吗??
    • 是的,我已经测试过了,它可以工作。我现在在刀片文件中使用该概念,但我认为这是一个 n+1 问题。这是一个雄辩的错误吗?
    • 你在刀片中得到了什么??
    • 我可以在刀片视图文件 {{ $stack->answersCount[0]->aggregate{{ $stack->answersCount[1]->aggregate 中使用它,具体取决于我是否要获取 correctwrong
    猜你喜欢
    • 1970-01-01
    • 2014-10-15
    • 2014-11-06
    • 2021-03-03
    • 2020-07-31
    • 2014-08-21
    • 2016-06-21
    相关资源
    最近更新 更多