Eloquent ORM 5.1 query returns incorrect result (compared to plain SQL)

user13955

I have a rather simple query in SQL

SELECT id, alias FROM users WHERE 
    `time_last_active` > (NOW() - INTERVAL 1 MINUTE) ORDER BY alias

which returns no (ie: zero) rows right now (which for the data I have is the correct/expected result).

I tried implementing the same query in Eloquent ORM using the following code

class Users extends Model
{
    protected $table   = 'users';

    public static function getActiveUsers ()
    {
        return self::where ('time_last_active', '>', "(NOW() - INTERVAL 1 MINUTE)")
            ->orderBy('alias')
            ->get(['id','alias'])
            ->toArray();
    }
}

This query executes without errors and returns a valid result (ie: an array of rows each containing "id" and "alias") BUT it returns every row in the table.

Does anybody have any idea what I'm doing wrong here? I've been staring at this for a while now and I'm just not seeing it.

Thanks for any tips.

jedrzej.kurylo

In order to use raw SQL like "(NOW() - INTERVAL 1 MINUTE)", you need to wrap it in a call to DB::raw(), otherwise it will be treated as a string, not the SQL syntax.

The following should work:

return self::where('time_last_active', '>', \DB::raw("(NOW() - INTERVAL 1 MINUTE)"))
  ->orderBy('alias')
  ->get(['id','alias'])
  ->toArray();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related