簡體   English   中英

使用關系計數對Laravel集合進行排序

[英]Sort Laravel collection with relationship count

我努力了幾天,但我無法讓它發揮作用。

這是一個例子,我有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-> questions-> count(); 每次測試我都會得到一些問題。

事實證明,當我這樣返回時,排序不起作用:

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

但是當我像這樣返回時它完全正常:

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

對我來說,這是一種非常奇怪的行為,我以前從未遇到過這樣的事情,如果有人能夠解釋,我會感激不盡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM