我已经努力了几天了,但我就是不能让它开始工作。
这里是一个例子,我有Laravel模型测试,问题,问题模型里面有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();
});
但是结果是一样的,集合没有排序。
如果这很重要,我会使用json响应,并且当我试图回显$ test ->问句->count()时,我会得到每个测试的问题数。
发布于 2016-04-13 08:43:03
结果发现,当我像这样返回时,排序就不起作用了:
return response()->json($tests);
但当我像这样回来的时候,一切都很好:
return response()->json($tests->values()->all());
对我来说,这是很奇怪的行为,我从来没有遇到过这样的事情,如果有人能解释的话,我会感激的。
https://stackoverflow.com/questions/36581355
复制