Skip to main content
Version: Next

Querying Relations

Querying Relations

Since all Mongoloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing a query to load the related models. In addition, all types of Mongoloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the query against your database.

For example, imagine a blog application in which a User model has many associated Post models:

import { Mongoloquent } from "mongoloquent";
import Post from "../yourPath/Post";

class User extends Mongoloquent {
static collection = "users";
static softDelete = true;
static timestamp = true;

static posts() {
return this.hasMany(Post, "userId", "_id");
}
}

You may query the posts relationship and add additional constraints to the relationship like so:

import User from "./yourPath/User";

const user = await User.find("10ab7e3d05d58a1ad250dd90");

const posts = await user.posts().where("active", true).get();

You are able to use any of the Mongoloquent query builder's methods on the relationship, so be sure to explore the query builder documentation to learn about all of the methods that are available to you.

Chaining orWhere Clauses After Relationships

As demonstrated in the example above, you are free to add additional constraints to relationships when querying them. However, use caution when chaining orWhere clauses onto a relationship, as the orWhere clauses will be logically grouped at the same level as the relationship constraint:

const posts = await user
.posts()
.where("active", true)
.orWhere("votes", ">=", 100)
.get();

The Mongoloquent query builder's can also use in polymorphic relationships.


Support us

Mongoloquent is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.

Sponsors

_

Partners