Skip to content

Many2Many Preload Conditions #7301

Closed Answered by fari-99
fari-99 asked this question in Q&A
Discussion options

You must be logged in to vote

after many thinkering, i decided to do this instead

        var userModel models.Users
	err := cc.DB.Debug().
		Preload("Companies", func(DB *gorm.DB) *gorm.DB {
			return DB.Select("DISTINCT(companies.id), companies.*"). // data not distinct
				Joins("LEFT JOIN user_companies ON companies.id = user_companies.companies_id"). // join with many2many table
				Where("status = ?", "active")
		}).Find(&userModel).Error

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by fari-99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant