问题描述
对于我的特定用例,我们有一个利用多态关联的现有 Rails 应用程序。现在我们收到了将某些数据公开到 Google Data Studio 的请求。这个想法是编写一个 SQL 查询来提取所需的数据,并让 Google Data Studio 使用查询作为数据源直接连接到数据库。现在我想知道我们将如何处理纯 SQL 查询中的多态关联。
示例
数据模型如下
Class User < ApplicationRecord
# ...
end
Class Reporter < ApplicationRecord
# ...
end
Class Article < ApplicationRecord
belongs_to :author,polymorphic: true # author can be either a user or a reporter
# ...
end
我们试图提取的数据是按作者和发表日期细分的文章计数。因此,如果作者不是多态关联,则查询将如下所示
SELECT articles.count,articles.author_id,articles.published_at,authors.name
FROM (
SELECT count(*),articles.published_at::DATE
FROM articles
GROUP BY articles.user_id,articles.published_at::DATE
ORDER BY articles.published_at::DATE,articles.user_id
) AS articles
LEFT JOIN authors ON articles.author_id = authors.id
现在,我将如何修改查询以适应多态关联?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)