Relationships
Vasta supports defining relationships between your models. You can define relationships such as hasMany and belongsTo to easily navigate between related models. Related models can be eager loaded or lazy loaded as needed.
For example, if you have a Person model and a Pet model, you can define the relationships as follows:
// In Person model
get pets() {
return this.hasMany(Pet, "person_id", "id");
}
// In Pet model
get owner() {
return this.belongsTo(Person, "person_id", "id");
}
Then you can lazy-load a person's pets or a pet's owner:
const person = await Person.find(1);
const pets = await person.pets; // Get all pets belonging to the person
You can also eager load relationships to optimize your queries:
const person = await Person.with("pets").find(1);
const pets = person.pets; // This will not trigger a new query, as the pets were eager loaded
Lazy loaded relationship queries can also be further constrained:
const person = await Person.findOrFail(3);
const bird = await person.pets.where("type", "bird").first();
Many-to-Many Relationships
You can define many-to-many relationships using the belongsToMany method. This requires a pivot table (or join table) to link the two models together.
For example, if a Pet can visit many Vets, and a Vet can see many Pets, you might use a vet_visits join table. You can define the relationship on the Pet model like this:
// In Pet model
get vets() {
// belongsToMany(RelatedModel, pivotTable, foreignPivotKey, relatedPivotKey)
return this.belongsToMany(Vet, "vet_visits", "pet_id", "vet_id");
}
You can interact with a many-to-many relationship just like any other, choosing to either eager load or lazy load the related models:
// Lazy loading
const pet = await Pet.find(1);
const vets = await pet.vets; // Get all vets this pet has visited
// Eager loading
const pets = await Pet.with("vets").get();
const firstPetVets = pets[0].vets;