douchujian8124 2018-09-11 06:53 采纳率: 100%
浏览 466

如何阻止GORM按ID对预载进行排序?

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 目详情-五一模拟赛详情页
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line