dimanche 16 mai 2021

Query returns when selecting *, but not when selecting specific column

In one of my model classes, I have the following relationship/query:

public function topTypes()
{
    return $this->votes()
        ->selectRaw('*, COUNT(comment_votes.type_id) as types_count')
        ->groupBy('comment_votes.type_id')
        ->orderBy('types_count', 'desc');
}

public function votes()
{
    return $this->hasMany('App\CommentVote', 'comment_id', 'comment_id');
}

When this gets executed, it returns successfully:

            "top_types" : [
              {
                "comment_id" : 461,
                "id" : 536,
                "type_id" : 0,
                "types_count" : 1,
                "user_id" : 58
              }
            ],

But really what I want it to return is just:

            "top_types" : [0],

Where 0 is the type_id.

When I try changing the selectRaw portion of the query to:

public function topTypes()
{
    return $this->votes()
        ->selectRaw('comment_votes.type_id, COUNT(comment_votes.type_id) as types_count')
        ->groupBy('comment_votes.type_id')
        ->orderBy('types_count', 'desc');
}

It just outputs an empty array:

            "top_types" : [

            ],

What am I doing wrong here?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire