Search code examples
sqllaravelrawsql

Why Raw sql doesnt work in laravel DB


I have this sentence:

$lastOperationUser = DB::select("SELECT last_operation FROM policies
                        INNER JOIN(users) 
                        ON (policies.user_id=users.id)
                        group by (user_id);");

If I execute in my phpmyadmin works fine but in laravel throw this error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'test.policies.last_operation' isn't in GROUP BY (SQL: SELECT last_operation FROM policies INNER JOIN(users) ON (policies.user_id=users.id) group by (user_id);)

My model is:

USERS         POLICIES
id            id
name          last_operation
              user_id      

One to many relationship

Any help please?


Solution

  • Given the description of what you're looking for from various comments, the following should be close to what you're after:

    SELECT user_id, MAX(last_operation) AS last_operation
      FROM policies
      JOIN users
        ON policies.user_id = users.id
      GROUP BY user_id
    

    Best of luck.