Chapter 19. SQL Joins
Persistent touts itself as a database-agnostic interface. How, then, are you supposed to do things that are inherently backend-specific? This most often comes up in Yesod when you want to join two tables together. There are some pure-Haskell solutions that are completely backend-agonistic, but there are also more efficient methods at our disposal. In this chapter, we’ll introduce a common problem you might want to solve, and then build up more sophisticated solutions.
Multiauthor Blog
Blogs are a well-understood problem domain, so let’s use that for our problem setup. Consider a blog engine that allows for multiple authors in the database, but supports blog posts that have a single author. In Persistent, we may model this as:
Author name Text Blog author AuthorId title Text content Html
Let’s set up our initial Yesod application to show a blog post index indicating the blog title and the author:
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
import
Control.Monad.Logger
import
Data.Text
(
Text
)
import
Database.Persist.Sqlite
import
Yesod
share
[
mkPersist
sqlSettings
,
mkMigrate
"migrateAll"
]
[
persistLowerCase
|
Author
name
Text
Blog
author
AuthorId
title
Text
content
Html
|
]
data
Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.