Rails通过多个连接从其他表中选择数据库表

时间:2017-12-21 14:40:05

标签: ruby-on-rails database postgresql select

我有型号类别(图像类别)

[map(sum, a)]

模型类别有许多订阅和订阅用户

class Category < ApplicationRecord
  has_many :images, foreign_key: 'category_id', dependent: :destroy
  has_many :subscriptions, foreign_key: "category_id", dependent: :destroy
  has_many :subscribed_users, :through => :subscriptions, :source => :user
end

我也有模特图片

class Subscription < ApplicationRecord
  belongs_to :user
  belongs_to :category
  validates :user_id, presence: true
  validates :category_id, presence: true
end
class User < ApplicationRecord
  has_many :images, foreign_key: 'user_id', dependent: :destroy
  has_many :categories, foreign_key: 'user_id', dependent: :destroy
  has_many :likes, foreign_key: "user_id", dependent: :destroy
  has_many :liked_images, :through => :likes, :source => :images
  has_many :comments, foreign_key: "user_id", dependent: :destroy
  has_many :commented_images, :through => :comments, :source => :images
  has_many :subscriptions, foreign_key: 'user_id', dependent: :destroy
  has_many :subscribed_categories, :through => :subscriptions, :source => :categories
end

有很多喜欢和评论(评论和喜欢的图像,而不是图像的类别)

class Image < ApplicationRecord
  belongs_to :user
  belongs_to :category
  has_many :likes, foreign_key: "image_id", dependent: :destroy
  has_many :liking_users, :through => :likes, :source => :user
  has_many :comments, foreign_key: "image_id", dependent: :destroy
  has_many :commenting_users, :through => :comments, :source => :user
end

我需要从数据库5中选择最受欢迎的类别。 最受欢迎的类别是同时拥有最多喜欢,评论和图像的类别。

我做了一个查询,选择所有图像,这些图像的喜欢和评论数量最多:

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :image
  validates :user_id, presence: true
  validates :image_id, presence: true
end
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :image
  validates :user_id, presence: true
  validates :image_id, presence: true
end

此外,我还查询哪些类别包含更多图像:

@top_images = Image.left_outer_joins(:likes).distinct.select('images.*, COUNT(likes.*) AS likes_count').left_outer_joins(:comments).distinct.select('images.*, COUNT(comments.*) AS comments_count').group(
        'images.id').order("likes_count DESC").order("comments_count DESC")

但我不知道如何选择所有具有最高图像数量,喜欢和评论的类别

0 个答案:

没有答案