我是 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 |
+ -------------------- +
符合我需要的 PS 常规 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;
那么,如何做到这一点,是否有任何关于复杂数据映射器查询的文档?