Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by in nested eager loading in sequelize not working

i have four model Tehsil, Ilr, Patwar, and Villages. and their association is

Tehsil -> 1:m -> Ilr -> 1:m -> Patwar -> 1:m -> Villages

i want to to apply order by on all four of my models.

Query:

var tehsilQuery = {
    include: [{
        model: Ilr,
        as: 'GirdawariKanoongo',
        include: [{
            model: Patwar,
            as: 'GirdawariPatwar',
            include: [{
                model: Villages,
                as: 'GirdawariVillages',
            }]
        }]
    }],
    order: [
        ['tehsil_name', 'ASC'],
        [ {model: Ilr, as: 'GirdawariKanoongo'}, 'kanoongo_name', 'ASC'],
        [ {model: Patwar, as: 'GirdawariPatwar'}, 'patwar_area', 'ASC'],
        [ {model: Villages, as: 'GirdawariVillages'}, 'village_name', 'ASC'],
    ]
};
return Tehsils.findAll(tehsilQuery);

[Error: 'girdawari_patwar' in order / group clause is not valid association]

order by is working if i remove Patwar and Villages(lat two model) from order.

like image 354
pirate Avatar asked Oct 23 '16 11:10

pirate


2 Answers

Another working example with nested ordering:

order: [  
  [ { model: chapterModel, as: 'Chapters' }, 'createdAt', 'ASC'], 
  [ { model: chapterModel, as: 'Chapters' }, 
    { model: partModel, as: 'Parts' }, 'createdAt', 'ASC'] 
],

where part and chapter have M:1 relation.

like image 70
ozgeneral Avatar answered Oct 26 '22 13:10

ozgeneral


Our scenario was with two nested include statements where the inner most nesting was not ordering correctly. By applying the ordering at the highest level of the findAll we were able to successfully return the ordered object.

model relationship as follows for our surveySet.findAll:

  • suveySet hasMany surveys
  • surveys belongsToMany questions

    order: [  
        [ { model: survey, as: 'survey' }, 'subjectId', 'ASC'], 
        [ { model: survey, as: 'survey' }, 
          { model: question, as: 'question' }, 'id', 'ASC'] 
    ]
    
like image 29
James Avatar answered Oct 26 '22 13:10

James