lundi 8 février 2016

Get latest distinct value of a filed in Laravel

I want to query the latest + distinct name.

I got the distinct part to work, but they're not the latest. I'm not sure how to do that in Laravel.


I’ve tried

$localDevices = Device::orderBy('created_at', 'desc')->groupBy('mac')->get();

        $localDeviceName = [];
        $i = 0;

        foreach ($localDevices as $localDevice) {
            foreach ($devices as $device) {
                if($localDevice->mac == $device->device_mac ){
                    $localDeviceName[$i]['name'] = $localDevice->name;
                    $src = '/images/photos/devices/'.Helper::img($localDevice->name).'.jpg';
                    $localDeviceName[$i]['img'] = $src;
                    $localDeviceName[$i]['mac'] = $device->device_mac;
                    $i++;
                }
            }
        }


Database

enter image description here


I got

array:1 [▼
  0 => array:3 [▼
    "name" => "Apple Watch"
    "img" => "/images/photos/devices/apple-watch.jpg"
    "mac" => "080027E2FC7D"
  ]
]

I want it to show ps4 because it is the latest.


Try #2

tried update my

orderBy('created_at', 'desc') to orderBy('created_at', 'asc')

I got the same result.


Try #3

tried placing orderBy after groupBy

Device::groupBy('mac')->orderBy('created_at', 'desc')->get();

I got the same result.


Any hints / suggestions on that will much appreciated !



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire