Skip to main content
Version: v1.1.x

hasManyThrough

hasManyThrough(Model, throughModel, foreignKey, throughForeignKey)

The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform. A Project model might access many Deployment models through an intermediate Environment model. Using this example, you could easily gather all deployments for a given project. Let's look at the collections required to define this relationship:

Collection structure

projects
_id - id
name - string

environments
_id - id
projectId - id
name - string

deployments
_id - id
environmentId - id
commitHash - string

Now that we have examined the collection structure for the relationship, let's define the relationship on the Project model:

Usage

import { Mongoloquent } from "mongoloquent";
import Environment from "./yourPath/Environment";
import Deployment from "./yourPath/Deployment";

class Project extends Mongoloquent {
static collection = "projects";

static deployments() {
return this.hasManyThrough(
Deployment,
Environment,
"projectId",
"environmentId"
);
}
}

// usage
const project = await Project.where("_id", "65ab7e3d05d58a1ad246ee87")
.with("deployments")
.first();

Also, you can pass collection name as a Model.

The softDelete is disabled in the target model when you pass the collection name as a model.

import { Mongoloquent } from "mongoloquent";
import Environment from "./yourPath/Environment";
import Deployment from "./yourPath/Deployment";

class Project extends Mongoloquent {
static collection = "projects";

static deployments() {
return this.hasManyThrough(
"deployments",
"environments",
"projectId",
"environmentId"
);
}
}

// usage
const project = await Project.where("_id", "65ab7e3d05d58a1ad246ee87")
.with("deployments")
.first();

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