JCC Express

Relationships

Introduction

JCC-Eloquent supports standard relationship methods directly on model classes.

Define relationships as instance methods returning relation builders.


Available relationship methods

From Model:

  • hasOne(related, foreignKey?, localKey?)
  • hasMany(related, foreignKey?, localKey?)
  • belongsTo(related, foreignKey?, ownerKey?)
  • belongsToMany(related, pivotTable?, foreignPivotKey?, relatedPivotKey?, parentKey?, relatedKey?)
  • morphOne(related, morphName, type?)
  • morphMany(related, morphName, type?)
  • morphTo(morphName?)

One-to-many example

TypeScript

Belongs-to example

TypeScript

Many-to-many example

TypeScript

If omitted, pivot table/key names are inferred from model names.


Polymorphic examples

TypeScript

Relationship query helpers

Static model methods:

  • has(relation, operator?, count?, boolean?, callback?)
  • whereHas(relation, callback?, operator?, count?)
  • orWhereHas(relation, callback?, operator?, count?)

Example:

TypeScript

Eager loading

Use with(...) to preload relations:

TypeScript

with also accepts object/callback style for constrained eager loading.


Summary

  • Define relations as model methods using hasOne/hasMany/belongsTo/belongsToMany/morph*.
  • Use with(...) for eager loading.
  • Use whereHas(...) when filtering by related data.