简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM