datamapper / dm-aggregates

DataMapper plugin providing support for aggregates on collections
http://datamapper.org/
MIT License
16 stars 15 forks source link

Incorrect query with M:M #3

Open solnic opened 13 years ago

solnic commented 13 years ago
#!/usr/bin/env ruby
#
# encoding: utf-8

require 'dm-sqlite-adapter'
require 'dm-aggregates'
require 'dm-migrations'

DataMapper::Logger.new $stdout, :debug
DataMapper.setup :default, "sqlite::memory:"

class Foo
  include DataMapper::Resource
  property :id, Serial
  has n, :foo_bars
  has n, :bars, :through => :foo_bars
end

class Bar
  include DataMapper::Resource
  property :id, Serial
  has n, :foo_bars
  has n, :foos, :through => :foo_bars
end

class FooBar
  include DataMapper::Resource

  belongs_to :foo, :key => true
  belongs_to :bar, :key => true
end

DataMapper.finalize.auto_migrate!

f = Foo.create
b1 = Bar.create
b2 = Bar.create
b3 = Bar.create
f.bars = [b1, b2, b3]
f.save

puts Foo.all(Foo.bars.id => [1,3]).inspect
puts Foo.all(Foo.bars.id => [1, 3]).count

Output:

 ~ (0.000046) SELECT "foos"."id" FROM "foos" INNER JOIN "foo_bars" ON "foos"."id" = "foo_bars"."foo_id" INNER JOIN "bars" ON "foo_bars"."bar_id" = "bars"."id" WHERE "bars"."id" IN (1, 3) GROUP BY "foos"."id" ORDER BY "foos"."id"
[#<Foo @id=1>]
 ~ (0.000037) SELECT COUNT(*) FROM "foos" INNER JOIN "foo_bars" ON "foos"."id" = "foo_bars"."foo_id" INNER JOIN "bars" ON "foo_bars"."bar_id" = "bars"."id" WHERE "bars"."id" IN (1, 3)
2