Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select all records with more than n child records

For the situation where Employee has_many Clients, I am trying to write an ActiveRecord query that will return all of the Employees that have n or more clients. It's simple enough to write a join query to find all of the Employees with at least 1 client but extending my query to this more general case has left me stumped.

Edit - I should add that I'm trying to do this entirely at the database level. I want to avoid iterating over the collection in Ruby.

like image 817
brad Avatar asked Nov 05 '12 06:11

brad


2 Answers

Thanks to mu and vijikumar, this is what I've come up with

Employee.select("employees.*").joins(:clients).group("employees.id").having("count(clients.id) > ?", n)
like image 114
brad Avatar answered Dec 09 '22 18:12

brad


@employees=Employee.select{|e|e.clients.length > n }

Active record query for the same..

@employees=Employee.find(:all, :joins=>"as emp inner join clients as c on c.employee_id=emp.id", :select=>"emp.id", :group=>'emp.id having count(c) > n')

it will give the employee id's who are all having more than n clients.

like image 22
vijikumar Avatar answered Dec 09 '22 18:12

vijikumar