Finding Records
The finder methods for DataMapper objects are defined in DataMapper::Repository. They include [], all(), first()
Finder Methods
DataMapper has methods which allow you to grab a single record by key, the first match to a set of conditions, or a collection of records matching conditions.
1 zoo = Zoo.get(1) # get the zoo with primary key of 1. 2 zoo = Zoo.get!(1) # Or get! if you want an ObjectNotFoundError on failure 3 zoo = Zoo.get('DFW') # wow, support for natural primary keys 4 zoo = Zoo.get('Metro', 'DFW') # more wow, composite key look-up 5 zoo = Zoo.first(:name => 'Luke') # first matching record with the name 'Luke' 6 zoos = Zoo.all # all zoos 7 zoos = Zoo.all(:open => true) # all zoos that are open 8 zoos = Zoo.all(:opened_on => start..end) # all zoos that opened on a date in the date-range
Conditions
Rather than defining conditions using SQL fragments, we can actually specify conditions using a hash.
The examples above are pretty simple, but you might be wondering how we can specify conditions beyond equality without resorting to SQL. Well, thanks to some clever additions to the Symbol class, it’s easy!
1 exhibitions = Exibition.all(:run_time.gt => 2, :run_time.lt => 5) 2 # => SQL conditions: 'run_time > 1 AND run_time < 5'
Valid symbol operators for the conditions are:
1 gt # greater than 2 lt # less than 3 gte # greater than or equal 4 lte # less than or equal 5 not # not equal 6 eql # equal 7 like # like 8 in # in - will be used automatically when an array is passed in as an argument
Order
To specify the order in which your results are to be sorted, use:
1 Zoo.all(:order => [:tiger_count.desc])
Available order vectors are:
1 asc # sorting ascending 2 desc # sorting descending
Compatibility
DataMapper supports other conditions syntaxes as well:
1 zoos = Zoo.all(:conditions => {:id => 34}) 2 zoos = Zoo.all(:conditions => ["id = ?", 34]) 3 4 # even mix and match 5 zoos = Zoo.all(:conditions => {:id => 34}, :name.like => '%foo%')
Talking directly to your data-store
Sometimes you may find that you need to tweak a query manually.
1 zoos = repository(:default).adapter.query('SELECT name, open FROM zoos WHERE open = 1') 2 # Note that this will not return Zoo objects, rather the raw data straight from the database
zoos will be full of Struct objects with name, and open attributes, rather than instances of the Zoo class. They’ll also be read-only. You can still use the interpolated array condition syntax as well:
1 zoos = repository(:default).adapter.query('SELECT name, open FROM zoos WHERE name = ?', "Awesome Zoo")
Counting
With DM-More’s DM-Aggregates included, the count method it adds will returns an integer of the number of records matching the every condition you pass in.
1 count = Zoo.count(:age.gt => 200) #=> 2