diff --git a/app/models/ml/model.rb b/app/models/ml/model.rb index 9c6e6248730e98fe283b5b0c0ef4c05efb124ef3..d187f732574bf3d77efa97c954c4b6e82481ce4c 100644 --- a/app/models/ml/model.rb +++ b/app/models/ml/model.rb @@ -30,9 +30,12 @@ class Model < ApplicationRecord scope :including_latest_version, -> { includes(:latest_version) } scope :including_project, -> { includes(:project) } scope :with_version_count, -> { - left_outer_joins(:versions) - .select("ml_models.*, count(ml_model_versions.id) as version_count") - .group(:id) + version_counts = Ml::ModelVersion + .select(:model_id, 'COUNT(*) as count') + .group(:model_id) + + joins("LEFT OUTER JOIN (#{version_counts.to_sql}) as version_counts ON version_counts.model_id = ml_models.id") + .select('ml_models.*, COALESCE(version_counts.count, 0) as version_count') } scope :by_name, ->(name) { where("ml_models.name LIKE ?", "%#{sanitize_sql_like(name)}%") } # rubocop:disable GitlabSecurity/SqlInjection scope :by_project, ->(project) { where(project_id: project.id) }