Querying a Database with DataMapper, Page 2
Querying the Database
It's incredibly easy to query the database using DataMapper. To view a list of all of the games found in the games table, ordering the results according to the name, create the following route:
get '/games' do
@games = Game.all(:order => [:name.asc])
erb :games
end
The @games variable can then be passed into a simple ERB template named games.erb:
<% @games.each do |game| %>
<%= game.name %><br />
<% end %>
Numerous finder variations are available; for instance, to retrieve a row associated with the game name Super Mario Kart, use the following statement:
@game = Game.first(:name => 'Super Mario Kart')
See the DataMapper documentation for much more information about finding data.
Creating Table Relations in DataMapper
Those developers who are keen to properly normalize their databases probably balked at the games table schema, because the platform column should actually be a foreign key which references a separate platforms table. In doing so, developers can avoid the possibility of data corruption occurring due to misspelled platform names, among other inconveniences.
DataMapper makes it easy to relate models using associations. In this case, we want to create a hasMany/belongsTo association because it could be useful to know not only what platform is associated with a particular game, but also which games are associated with a particular platform. To do so, you'll need to create a new Platform model and then update the Game model in order to define the associations. The Platform model looks like this:
class Platform
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :games
end
The updated Game model looks like this:
class Game
include DataMapper::Resource
property :id, Serial
property :name, String
belongs_to :platform
end
With the updated models in place and the tables populated with the appropriate associations, retrieving a platform name associated with a particular game is as easy as this:
<%= @game.platform.name %>
This is but a simple example of DataMapper's incredibly powerful associative capabilities. See the documentation for all of the details.
Conclusion
Are you doing anything cool with DataMapper? Share your experiences in the comments!
About the Author
Jason Gilmore -- Contributing Editor, PHP -- is the founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board.
