简体   繁体   English

在活动记录中使用Arel的关系计数

[英]Count of a relation using arel in active record

I'm having a really rough time figuring out how to do this query and others like it in arel from active record. 我真的很艰难,需要从活动记录中找出如何在arel中执行此查询和其他类似的查询。

  select users.id, 
         users.name, 
         maps.count as map_count, 
  from users
  left join (select user_id, count(map_id) as count from maps_users group by user_id) maps on users.id = maps.user_id

On the surface, it looks just like Nik's example here (http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/): 从表面上看,它看起来像Nik的示例(http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/):

photo_counts = photos.
group(photos[:user_id]).
project(photos[:user_id], photos[:id].count)

users.join(photo_counts).on(users[:id].eq(photo_counts[:user_id]))

But I can't get it to work in rails using active record. 但是我无法使用活动记录在轨道上工作。 I think the equivalent should be something like this, but it errors out :( 我认为等效应该是这样的,但是它会出错:(

  maps = Map.arel_table
  map_counts = Map.group(maps[:owner_id]).
                   select(maps[:owner_id]).
                   select(maps[:id].count.as("map_count"))
  users = User.joins(map_counts).on(User.arel_table[:id].eq(map_counts[:map_count]))

Any ideas on how to do it? 关于如何做的任何想法?

Well first replace the select with project. 首先,将select替换为项目。 In relational algebra SELECT (restriction) is the WHERE clause. 在关系代数中,SELECT(限制)是WHERE子句。

Secondly you can do subselections. 其次,您可以进行子选择。

sub_restriction = b.
                   where( b[:domain].eq(1) ).
                   project( b[:domain] )

restriction = a.
               where( a[:domain].in sub_restriction )

"sub selections" DONE! “子选择”完成! :-) :-)

Yeah, that article really made me want to learn Arel magic, too. 是的,那篇文章确实使我也想学习Arel魔术。

All the "do something intelligent with Arel" questions on Stackoverflow are getting answered with SQL. 所有关于Stackoverflow的“用Arel做一些聪明的事情”的问题都可以通过SQL得到解答。 From articles and research, then, I can say that Arel is Not ActiveRecord. 从文章和研究来看,我可以说Arel不是ActiveRecord。 Despite the dynamic formulation of queries, Active doesn't have the power to map the results of a fully formed Arel projection. 尽管查询是动态制定的,但是Active没有能力映射完全形成的Arel投影的结果。

You get the ability to specify operators with 您可以使用指定操作符

https://github.com/activerecord-hackery/squeel

but no subselects. 但没有子选择。

Updated: OMG, I answered this question 5 years ago. 更新:天哪,我5年前回答了这个问题。 No kidding the link was dead :) 没有开玩笑的链接是死的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM