Laravel OrderBy relationship count

后端 未结 5 952
Happy的楠姐
Happy的楠姐 2020-11-28 06:24

I\'m trying to get the most popular hackathons which requires ordering by the respective hackathon\'s partipants->count(). Sorry if that\'s a little difficul

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 07:07

    I had similar issue and using sortBy() is not suitable because of pagination, exactly as Sabrina Gelbart commented in previous solution. So I used db raw, here's simplified query:

    Tag::select( 
    array(
        '*',
        DB::raw('(SELECT count(*) FROM link_tag WHERE tag_id = id) as count_links')) 
    )->with('links')->orderBy('count_links','desc')->paginate(5);   
    

提交回复
热议问题