pmusa
1 week ago
149
10
Eloquent

orderBy() not compatible with distinct()

Posted 1 week ago by pmusa

I have 3 models: User Post Comment

Users can leave comments on a post.

I have a method within my Post model that allows me to list all users who left a comment on a post :

    /**
     * Get distinct commentators on a commentable model.
     *
     * @usage  $distinctCommentators = Post::find('post_UUID')->commentableCommentators()->get();
     *
     * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
     */
    public function commentableCommentators(): belongsToMany
    {
        return $this->belongsToMany($this->retrieveUserModel(), 'comments', 'commentable_id', 'user_id')
            ->where('commentable_type', array_search(static::class, Relation::morphMap()) ? : static::class)
            ->distinct('user_id');
    }

I'd like to sort that users list so that the user that commented first appears first. So i appended this :

->orderBy('comments.created_at')

Which won't work since it collides with the distinct().

Thank you for your help.

Please sign in or create an account to participate in this conversation.