Consultations in Laravel

1

I'm trying to run a query in Laravel , the terminal works perfectly, but when I enter in Laravel , it returns me empty, eg:

Query:

   SELECT 
    MAX(positions.id),
    devices.name,
    positions.deviceid,
    positions.servertime,
    positions.devicetime,
    positions.fixtime,
    positions.latitude,
    positions.longitude
FROM positions
INNER JOIN devices 
    ON positions.deviceid = devices.id
GROUP BY positions.deviceid

no Laravel :

$ultimasPosicoes = PositionAll::select('SELECT 
            MAX(positions.id),
            devices.name,
            positions.deviceid,
            positions.servertime,
            positions.devicetime,
            positions.fixtime,
            positions.latitude,
            positions.longitude
            FROM
            positions
            INNER JOIN devices ON positions.deviceid = devices.id
            GROUP BY
            positions.deviceid');
    
asked by anonymous 07.03.2018 / 19:13

2 answers

2

You can use DB::table() to make the query indicating the fields you need, it would look something like this:

$positions = DB::table('positions')
->selectRaw('MAX(positions.id),
    devices.name,
    positions.deviceid,
    positions.servertime,
    positions.devicetime,
    positions.fixtime,
    positions.latitude,
    positions.longitude')
->join('devices', 'positions.deviceid', '=', 'devices.id')->groupBy('deviceid')->get();

Another way that was commented by Leandro RR is to use Eloquent pure, in case instead of using Facade DB we would use only Model , thus:

$positions = Position::selectRaw('MAX(positions.id),
        devices.name,
        positions.deviceid,
        positions.servertime,
        positions.devicetime,
        positions.fixtime,
        positions.latitude,
        positions.longitude')
    ->join('devices', 'positions.deviceid', '=', 'devices.id')
    ->groupBy('positions.deviceid')
    ->get();

Reference: Database: Query Builder

    
07.03.2018 / 19:20
1

Thanks in advance for your help, we were able to solve it as follows:

$ultimasPosicoes =  PositionAll::selectRaw('MAX(positions.id),
                                        devices.name,
                                        positions.deviceid,
                                        positions.servertime,
                                        positions.devicetime,
                                        positions.fixtime,
                                        positions.latitude,
                                        positions.longitude')
            ->join('devices', 'positions.deviceid', '=', 'devices.id')
            ->groupBy('deviceid')
            ->get();
    
07.03.2018 / 21:07