Querying many to many Unscoped associations (deleted)

Viewed 146

I have a gorm many2many model like this with a custom join table :

type Vehicle struct {
    gorm.Model
    Registration string 
    Users  []User `gorm:"many2many:vehicle_users` 
}

type VehicleUser struct {
    gorm.Model
    VehicleID uint
    UserID uint
}

type User struct {
    gorm.Model
    Vehicles []Vehicle  `gorm:"many2many:vehicle_users`
    Name     string
    OIB      int
}

I want to make a query getting all deleted and undeleted users and their associations, again deleted and undeleted.

(gorm 1.21.16) and MySql 8.0

When i make a query like this :

u := User{}

db.Unscoped().Preload("Vehicles", func(db *gorm.DB) *gorm.DB {
        return db.Unscoped()
    }).Find(&u)

gorm makes 3 SQL queries in the background

[52.918ms] [rows:4] SELECT * FROM `users`

[14.314ms] [rows:3] SELECT * FROM `vehicle_users` WHERE `vehicle_users`.`user_id` IN (1,2,3,4) AND `vehicle_users`.`deleted_at` IS NULL 

[0.576ms] [rows:2] SELECT * FROM `vehicles` WHERE `vehicles`.`id` IN (4,27)

The problem is with the query on the join table vehicle_users, it queries just undeleted associations. I cant seem to find how to modify query on the join table to remove deleted_at IS NULL clause. Whats the proper way to do it?

0 Answers
Related