3/20/2023 0 Comments Laravel eloquent order by>leftJoin('replies', 'channels.id', '=', 'replies. So if you add groupBy method, you have to use orderByRaw method and should be implemented like the following. See detail this problem at this stackoverflow question. Because in Sql nature, Group By clause run first before Order By clause. If you want to add groupBy method to the query, you have to pay special attention to your orderBy clause. You can chain this method with a where () call for even more fine-grained results. You may recall using a method called sortDesc(), which was used to sort the records in descending order. Although you could use the sortDesc () method to reorder the collection within the list->links call, using the orderBy () method provides more flexibility and allows you to include additional filtering conditions later. >leftJoin('replies', 'channel.id', '=', 'replies.channel_id') In a previous part of this series, you learned how to obtain database records using the all() method from within an Eloquent model. Then you can call $user->sortedChannels('desc') to get the list of channels order by replies created_at attribute.įor condition like channels (which may or may not have replies), just use leftJoin method. >orderBy('replies.created_at', $orderBy) The following solution is fully tested and work well. I think use join method in combination with relationship method is the solution. That's why you can't achieve what you want with eager loading with method. >join('replies', 'replies.channel_id', '=', 'channels.id')Īccording to my knowledge, eager load with method run 2nd query. Users Table Result we are using a string in order by like pending, approved, and rejected status then following examples are useful. Return $this->belongsToMany('App\Channel') you can also give array in order by method, Laravel gives the facility to sort manual array in order by, following example through a specific array in order by. ![]() ![]() yes i did get the expected result but it would not load all channel if there's no reply. >orderBy('replies.created_at') // errorĪlso, i tried this. Return $this->belongsToMany('App\Channel', 'channel_user') How can i order the user's channel just like this? Now, i want to order the user's channel by its channel's current reply. channel have hasMany('App\Reply', 'channel_id', 'id')->oldest() Ĭhannel-2 has latest replies than channel-1.user have belongsToMany('App\Channel').
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |