【问题标题】:Sort Laravel collection with relationship count使用关系计数对 Laravel 集合进行排序
【发布时间】:2016-08-03 13:01:58
【问题描述】:

我努力了几天,但我无法让它发挥作用。

这里是例子,我有 Laravel 模型测试,问题,问题模型里面有 test_id 属性。我想按给定测试的 test_id = id 存在的问题数对测试集合进行排序。

我都试过了

$tests = Test::select(
        array(
            '*',
            DB::raw('(SELECT count(*) FROM questions WHERE test_id = id) as count_questions'))
    )->with('questions')->orderBy('count_questions','desc')->paginate(5);

$tests = Test::has('questions', '>', 3 )->with('questions')->get()->sortBy(function($test)
    {
        return $test->questions->count();
    });

但结果相同,集合没有排序。

如果这很重要,并且当我尝试回显 $test->questions->count(); 时,我会使用 json 响应每次测试我都会得到一些问题。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    事实证明,当我这样返回时,排序不起作用:

    return response()->json($tests);
    

    但是当我这样返回时它工作得非常好:

    return response()->json($tests->values()->all());
    

    对我来说这是非常奇怪的行为,我以前从未遇到过这样的事情,如果有人能解释一下,我将不胜感激。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 2019-01-26
      • 2023-03-28
      • 2017-04-26
      • 2017-05-02
      • 2019-02-14
      • 1970-01-01
      • 2015-03-27
      相关资源
      最近更新 更多