Nienna
Nienna

Reputation: 453

Getting an error when trying to groupBy in laravel

I'm trying to create a page that will show the amount of approved posts and group them by created_at column.

When I use the code that I've written I get this error

ErrorException SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'blog.posts.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from posts where status = approved group by created_at) (View: /home/workspace/Documents/projects/blog/Modules/Posts/Resources/views/index.blade.php)

Here is my code

$approved = Post::where('status', 'approved')->groupBy('created_at')->get();

dd($approved);

Upvotes: 0

Views: 1733

Answers (2)

Zafar Ahmed
Zafar Ahmed

Reputation: 369

$data = DB::table('posts')
                ->groupBy('created_at')
                ->having('status','approved')
                ->get();

just change where with having in your condition

Upvotes: 2

joekenpat
joekenpat

Reputation: 387

when using groupby clause always add the column name you are grouping by in the select statement EG:

$approved = Post::select('created_at')
                  ->where('status', 'approved')
                  ->groupBy('created_at')->get();

dd($approved);

Upvotes: 0

Related Questions