加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 复杂的DataMapper查询关联

发布时间:2020-12-17 04:23:13 所属栏目:百科 来源:网络整理
导读:我是DataMapper ORM的初学者,所以我对复杂的查询有疑问. 首先,这是简化的数据对象: class User property :id,Serial property :login,String has n,:actionsendclass Item property :id,Serial property :title has n,:actions has n,:users,:through = :ac
我是DataMapper ORM的初学者,所以我对复杂的查询有疑问.

首先,这是简化的数据对象:

class User  
    property :id,Serial
    property :login,String

    has n,:actions
end

class Item
    property :id,Serial
    property :title

    has n,:actions
  has n,:users,:through => :actions
end

class Action
    property :user_id,Integer
    property :item_id,Integer

    belongs_to :item
    belongs_to :user
end

这就是db中的数据的样子:

+ ------- + + ------- + + ------- +
| Users   | | Items   | | Actions |
+ ------- + + ------- + + ------- +
| 1  | u1 | | 3  | i1 | | 1  | 4  |
| 2  | u2 | | 4  | i2 | | 1  | 3  |
| ....... | | 5  | i3 | | 1  | 4  |
+ ------- + | ....... | | 1  | 5  |
            + ------- + | 1  | 6  |
                        | 1  | 3  |
                        | ....... |
                        + ------- +

因此,例如用户1已经查看了一些项目N次.而我无法弄清楚,如何选择与用户相关的项目及其行动金额.

例如,用户1的结果应该是这样的:

+ -------------------- |
| Items (item_id,num) |
+ -------------------- |
| 3,2                 |
| 4,2                 |
| 5,1                 |
| 6,1                 |
+ -------------------- +

附:符合我需求的常规SQL查询:

SELECT i.id,i.title,COUNT(*) as 'num'
FROM actions a
JOIN items i on i.id = a.item_id
WHERE a.user_id = {USERID}
GROUP by a.id
ORDER BY num DESC
LIMIT 10;

那么,如何做到这一点,是否有任何关于复杂数据映射器查询的文档?

解决方法

据我所知,datamapper或其任何插件中都没有group by运算符.如果有,它将与聚合函数(count,min,max,avg)一起进入dm-aggregates.这使得在不使用sql的情况下很难在一个查询中复制您想要的内容.

你可以尝试这样的事情:

require 'dm-aggregates'

Item.all.map do |item|
  [item.title,item.actions.count(:user_id=>@user_id)]
end

但是,您可以轻松地将您的sql包装在fn中.

class User
  def item_views
  repository.adapter.query "SELECT i.id,COUNT(*) as 'num'
    FROM actions a
    JOIN items i on i.id = a.item_id
    WHERE a.user_id = {USERID}
    GROUP by a.id
    ORDER BY num DESC
    LIMIT 10;"
  end
end

repository.adapter.query返回一个结构数组,所以你可以做类似的事情

user.item_views[0].title

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读