Ad

Laravel/Octobercms Eager Load Relation With One Record

- 1 answer

I am having a Main table "devices" each device has a oneToMany relation with "devicelogs"

Device Model

class Device extends Model
{
    public $hasMany = [
        'devicelogs' => 'Myhome\Myplugin\Models\Devicelog'
    ];
}

DeviceLog Model:

class Devicelog extends Model
{
    public $belongsTo = [
        'device' => 'Myhome\Myplugin\Models\Device'
    ];
}

I want to eager load devicelogs relations with only one record in response with latest log for that relation.

I've tried doing:

$d = Device::with([
    'devicelogs' => function ($query) {
        $query->latest('created_at')->limit(1)->get();
    }
])->get();

with this i only get one device with relation devicelogs having one latest record. I want all device with one device log.

I tried following:

$d = Device::with([
    'devicelogs' => function ($query) {
        $query->first();
    }
])->get();

with this i only get one device with relation devicelogs having one first record.

When I do :

$d = Device::with([
    'devicelogs' => function ($query) {
        $query->orderBy('created_at','desc');
    }
])->get();

I do get all devices loaded with relations collection in desc order. But issue is i dont want entire devicelogs, I just want latest/last one for each device.

So I tried doing:

$d = Device::with([
    'devicelogs' => function ($query) {
        $query->orderBy('created_at','desc')->limit(1);
    }
])->get();

This again only gets latest/last devicelogs with single record for only one device. rest all devices get empty devicelogs relation.

In record I have atleast 2 or more devicelog for each device. What i want is to have onely one and last/latest devicelog to return for each device when i run eager loading.

Im not sure where exactly im doing wrong.

Ad

Answer

There is a way around this which you may benefit from. In Laravel you would simply define a new relation and make it a hasOne.

Since OctoberCMS still has access to use the Laravel style relation methods. You could do something like the following;

in your Device.php model

public function latestDeviceLog()
{
    return $this->hasOne('Myhome\Myplugin\Models\Devicelog')->latest();
}

then you can access with.

Device::with('latestDeviceLog')->get();
Ad
source: stackoverflow.com
Ad