usage
Dream provides many useful tools for accessing and manipulating associations. Leveraging these powerful tools will enable you to easily bring forward complex, nested relationships throughout your app without ever manually writing a single line of SQL yourself.
Loading
With associations already created in the database, there are several ways to access them. The most common way to do this would be to leverage the preload method, which will enable you to load an association onto your record as you are loading the record itself, like so:
const user = await User.preload('posts').execute()
user.posts
// [Post{}, Post{}, ...]
Additionally, you can retroactively load associations onto an instance using the load method:
let user = await User.firstOrFail()
user = await user.load('posts').execute()
user.posts
// [Post{}, Post{}, ...]
When loading and preloading, additional where statements can be passed in, and many associations can be chained together:
let user = await User.firstOrFail()
user = await user.load('posts', { body: null }).load('pets').execute()
user.posts
// [Post{ body: null }, Post{ body: null }, ...]
user.pets
// [Cat{}, Dog{}]
associationQuery
In addition to loading associations onto an existing instance, you can also construct a new query targeting your association using associationQuery:
const posts = await user.associationQuery('posts').all()
// [Post{}, Post{}, ...]
Using associationQuery, you can add additional statements to your query before loading, like so:
const posts = await user
.associationQuery('posts')
.where({ body: null })
.innerJoin('comments', { body: null })
.all()
// [Post{ body: null }, Post{ body: null }, ...]