mardi 6 février 2018

Laravel 5: How to create a custom attribute for a collection, then sort with it

I'd like to do complex sorting on the results of a model.

E.g. I have \App\Classes::where(something), and from there I'd like to append an additional attribute for each class, then sort using that attribute, i.e. (inspired by the approach in https://laracasts.com/discuss/channels/eloquent/is-there-any-way-to-add-attribute-to-objects-in-collection)

$classes = \App\Classes::where(something)
foreach ($classes as &$class) {
        $classes['custom_score'] = some logic that changes per $class;
}
$classes_sorted = $classes->orderBy('custom_score')

But this code gives me the SQL error: "Column not found: 1054 Unknown column 'custom_score' in 'order clause'"

I don't want to actually write to the database for this custom_score, since it will change often and uniquely, with every user interaction.

What would be a good solution?

Thanks a lot in advance



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire