Sorting data with Eloquent

后端 未结 5 614
傲寒
傲寒 2021-01-11 12:49

I\'m new to laravel (switched from CI) and eloquent ORM is still a bit of a mystery at some point!

Here is my problem :

I\'d like to sort data from my db usi

5条回答
  •  天涯浪人
    2021-01-11 13:30

    The issue you are facing is because the Relationship that you've defined is just giving you the the Comments that are associated with the posts and an "Order By" on that result will just sort the comments since the comments are what is coming out, so what you could do is that also define that "Comments" belongs to "Post" in the Comments model and then find which Post the Comment is associated with and then use the usort() function to run a manual comparison an example would be (I'm writing the code in Laravel 3 but you could re-write it for any other version):

    So, Assuming that your Comments table has a foreign key called postID which defines the relationship with the Posts table and the Timestamp in the Posts table is the default created_at and the Users table is connected to the Comments table with the foreign key userid,

        $userid = $user->id;
        $comments = Comments::where_userid($userid);
        function commentsort($first, $second){
          if (getCommentPost($first) == getCommentPost($second)) {
            return 0;
          }
         return (getCommentPost($first) < getCommentPost($second)) ? -1 : 1;
        }
    
        function getCommentPost($comment){
        return Post::where_postid($comment->postid)->first()->created_at;
        }
    
        usort($comments, "commentsort");
    

    That should help fix this, In reality this isn't included in Laravel because it's a framework and functions like these which perform specific functions aren't generally included in the framework because there is limited scope of use, that being said you could also include this function in the default DB class so as to use this functionality universally in the project.

提交回复
热议问题