几天来我一直在努力,但就是无法发挥作用。
举个例子,我有Laravel模型Test,Questions,Question模型里面有Test_id属性。我想根据给定测试的Test_id=id存在的问题数量对Test集合进行排序。
两种我都试过了
$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响应;每次考试我都会得到很多问题。
当我像这样返回时,排序不起作用:
return response()->json($tests);
但当我像这样返回时,它运行得非常好:
return response()->json($tests->values()->all());
对我来说,这是一种非常奇怪的行为,我以前从未面对过这样的事情,如果有人能解释,我会很感激。