Group Eloquent

Published 9 months ago by thesogafoi

hey Guys i try to Group my Posts By Year and month but give me an error i searched a lot but i cannot fix this can U help me

public function scopeArchives($query){
        $query->selectRaw(' count(*)  published ,year(created_at) year, monthname(created_at) month')
            ->groupBy('year');
    }

And this is My Controller COde


 $archives = Post::latest()->archives()->get();

and this is my error

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'homestead.posts.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select count(*) published ,year(created_at) year, monthname(created_at) month from `posts` group by `year` order by `created_at` desc)


BezhanSalleh

This is a warning stating that your query is ambiguous, came in MySQL 5.7. the easy options is to add the month in the group by too: ->groupBy('year','month'); you will be ok.

thesogafoi

@bezhansalleh i did it but give me same error

i dont know why when i change the function to this

public static function archives(){
        return Post::selectRaw(' count(*)  published ,year(created_at)      
             year, monthname(created_at) month')
            ->groupBy('year');
    }

and then use view composer every things work and i don't know how this fixed

BezhanSalleh

as long as it works! right...

thesogafoi

@BezhanSalleh Any way thx for answer

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