mercredi 29 mars 2017

Laravel 5.4 Eloquent relationship sorting

I have two database tables called deliverables, and deliverable_version.

Deliverable hasMany Deliverable_Version.

Deliverable table has id column, and has a function to get the most recent version with this code:

public function getRecentVersion()
{
    $deliverable_version_max = $this->versions()->max('version');

    $deliverable_version = DeliverableVersion::where([
        'version'=>$deliverable_version_max,
        'deliverable_ID'=>$this->id,
    ])->first();

    return $deliverable_version;
}

Deliverable_version table has id, deliverable_ID, title, message, deadline, version, created_at, updated_at.

I was wondering how I would perform an operation where I can select all deliverables, and sort it by the columns of the most recent version.

Here is my attempt at it, which isn't working because it selects all the versions when I join the tables, not just the recent version:

$deliverables = Accounts::find($owner_account_ID)->deliverables();
    $deliverables = $deliverables->join('deliverable_version', 'deliverable.id', '=', 'deliverable_version.deliverable_ID');
    $deliverables = $deliverables->search($search);
    $deliverables = $deliverables->orderBy('deliverable_version.updated_at', 'desc');
    $deliverables = $deliverables->paginate(4);

Any help is appreciated. Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2nufZI0
via IFTTT

Aucun commentaire:

Enregistrer un commentaire