0

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);

2

2 Answers 2

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

just change where with having in your condition

Sign up to request clarification or add additional context in comments.

Comments

0

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);

3 Comments

If I do that, then I only get the created_at and I would like to get all the columns not just the created_at column
@Nienna then add all the columns names in the select statement if you need all it's a must
That is what I thought so I typed Post::select('id', 'status,' 'created_at'), but then I got the same error as my question though this time it has 'blog.posts.status instead of 'blog.posts.id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.