Your Question

How to perform count on association without including the deleted rows.

The document you expected this should be explained

The relationship models are:

type Subcategory struct { ID uint64 json:"-" gorm:"primaryKey;autoIncrement" Name string json:"name" binding:"required" CreatedAt time.Time json:"created_at" gorm:"autoCreateTime" UpdatedAt time.Time json:"updated_at" gorm:"autoUpdateTime" DeletedAt gorm.DeletedAt json:"deleted_at" TemplateCount uint64 json:"template_count" gorm:"-:migration;->" }

type Template struct { ID uint64 json:"-" gorm:"primaryKey;autoIncrement" SubcategoryID uint64 json:"-" gorm:"not null; index" Title string json:"title" binding:"required" CreatedAt time.Time json:"created_at" gorm:"autoCreateTime" UpdatedAt time.Time json:"updated_at" gorm:"autoUpdateTime" DeletedAt gorm.DeletedAt json:"deleted_at" Subcategory Subcategory json:"subcategory" gorm:"constraint:OnUpdate:CASCADE;OnDelete:CASCADE;" }

QUERY: models.DB.Preload(clause.Associations). Select("subcategories.*", "COUNT(template.subcategory_id) as template_count"). Joins("LEFT JOIN templates template ON subcategories.id = template.subcategory_id"). Group("subcategories.id"). Find(&subcategories);

This returns subcategories with template_count field but it includes the soft deleted rows on the templates assoc table.

Expected answer

This is supposed to return count of templates that are not deleted.

How to perform COUNT on JOINS without including the deleted rows of the Joined table.

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days