In my database I have a users table, joined via a many-to-many table to schools. A school has many jobs. I'm trying to return all the schools and their jobs for a specific user. This is my code so far:
var user User
err := db.Where("id = ?", userID).Preload("Schools")
.Preload("Schools.Jobs", func(db *gorm.DB) *gorm.DB {
return db.Order("job.job_reference DESC")
}).First(&user).Error
return &user.Schools, err
Gorm is then executing the following queries:
SELECT * FROM `user` WHERE (id = 'foo') ORDER BY `user`.`id` ASC LIMIT 1
SELECT * FROM `school`
INNER JOIN `user_school` ON `user_school`.`school_id` = `school`.`id`
WHERE (`user_school`.`user_id` IN ('foo'))
SELECT * FROM `job` WHERE (`school_id` IN ('1','2'))
ORDER BY job.job_reference DESC,`job`.`id` ASC
The first two generated SQL queries are exectly what I expected however the last query tries to sort by the criteria I provided AND a default sort by ID. If I remove my specific sort instructions it still tries to sort by ID. How can I stop it from doing that?
sqlx
package is my preferred method. – Lantz