Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

What do you mean with "create an own custom attribute"?
Normally you may use the query builder orderBy() method with Eloquent models too, or at least the Collection sortBy().

Last updated 2 years ago.
0

I mean that if I for example create something like this in my model:

public function getCountAttribute()
{
    return $this->someNumber + 
        OtherModel::where('something', $this->id)->pluck('someNumber');
}

I can then reach that value by $model->count, but can I somehow order by that attribute?

Last updated 2 years ago.
0

Your example leads to sorting the collection at application level, but that may perform poorly without eager loading.
So, first try to define a proper Eloquent relation and simplify your accessor, e.g.

class SomeModel extends Eloquent {
    
    ...
    
    public function getCountAttribute()
    {
        return $this->someNumber + $this->relatedModel->someNumber;
    }
    
    ...
    
}

At that point, you could try something like this:

$orderedModels = SomeModel::with('relatedModel')->get()->sortBy('count');

This may need some tuning but I hope it points you in a good direction.

Last updated 2 years ago.
0

Yeah, I will not use what I had in my example, it was just a quickly put together example to show what I wanted to achieve.

I was not aware of the sortBy method, that's exactly what I am looking for. Thank you very much.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mengidd mengidd Joined 1 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.