php - How can I sort a table of Laravel Eloquent objects by a custom attribute? -
i have laravel 4.2 project (though i'll upgrade laravel 5, i'm interested in answers apply either version of laravel). define custom attributes models make easier calculate , display values. (see laravel documentation how works.) e.g.:
public function getfoobarattribute() { // complex calculations, etc. return $result; }
then in view can {{ $object->foo_bar }}
print result of calculation.
often such code appear column of <table>
displaying list of objects. want make table sortable column. best way that?
the main solution have come far convert calculations in function equivalent sql (and there eloquent / querybuilder syntax). however, error-prone, makes code harder read, , difficult maintain (since must changed if attribute function ever is).
another solution sort resulting collection
manually, i'm under impression doing slower. (is true?)
how else can accomplish this?
the way be, stated, convert calculations or code in custom attributes sql. if you're doing might retrieve custom attribute sql well. try accomplish scope: http://laravel.com/docs/4.2/eloquent#query-scopes
lets consider example: have table products column price , tax. lets have custom attribute pricetotal follows:
public function getpricetotalattribute() { return ($this->price + $this->tax); }
in case define scope replace attribute.
public function scopepricetotal($query) { return $query->selectraw($this->table . '.*, (price + tax) pricetotal') ->orderby('pricetotal'); }
of course simple example, code far more complex. more verbose, because require call scope every time need custom attribute. it's way make sql aware of custom attribute , able order sql result accordingly.
your best bet using using collection order result. it's pretty fast, doubt slow down application much. documentation shows how order collection: http://laravel.com/docs/4.2/eloquent#collections , here's useful article on collections: http://codebyjeff.com/blog/2015/05/stupid-collection-tricks-in-laravel
Comments
Post a Comment