2016-04-12 77 views
1

我努力工作了几天,但我不能得到它的工作。排序Laravel收集关系计数

这里是例子,我有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(); 
    }); 

,但结果是一样的,收集未排序。

我使用json响应如果重要,当我尝试echo $ test-> questions-> count();每次测试我都会收到一些问题。

回答

0

原来,当我回到这样的排序不起作用:

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

但是当我回到这个样子工作完全正常:

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

对我来说这是很奇怪行为,我从来没有遇到过这样的事情,如果有人能解释它,我会感激。