Sandro Adamia
Sandro Adamia

Reputation: 463

SailsJS How to apply sort by on an instance method and instance method which is populated from another model?

Hi consider this example

//        surname_and_name: function(){
//            return (this.name_last==null ? '' : this.name_last + ' ') +
//                (this.name_middle==null ? '': this.name_middle + ' ') +
//                (this.name_first==null ? '' : this.name_first + ' ')  +
//                (this.name_prefix==null ? '' : this.name_prefix + ' ') +
//                (this.name_suffix==null ? '' : this.name_suffix);
//        },

     toJSON: function() {
        var obj = this.toObject();
        obj.surname_and_name = (obj.name_last==null ? '' : obj.name_last + ' ') +
            (obj.name_middle==null ? '': obj.name_middle + ' ') +
            (obj.name_first==null ? '' : obj.name_first + ' ')  +
            (obj.name_prefix==null ? '' : obj.name_prefix + ' ') +
            (obj.name_suffix==null ? '' : obj.name_suffix);
       return obj;
    }

i am trying to query and sort it by "surname_and_name" computed field. i tried commented code as well, i get this error, for method

co_user.find(sort : {surname_and_name: 'asc' }).exec(error,res) 

Error: ER_BAD_FIELD_ERROR: Unknown column 'co_user.surname_and_name' in 'order clause'

Upvotes: 2

Views: 213

Answers (1)

sgress454
sgress454

Reputation: 24958

The toJSON method is called when sending model data back from the server, not during queries. Therefore, the surname_and_name property is not available during queries; only real model attributes can be used as query parameters. If this kind of sort is important to you, I'd recommend making an actual surname_and_name attribute for your model which gets automatically calculated every time the model is saved, using the model class's afterCreate() and afterUpdate() lifecycle callbacks.

Upvotes: 1

Related Questions