【发布时间】: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 响应每次测试我都会得到一些问题。
【问题讨论】: