For the complete documentation index, see llms.txt. This page is also available as Markdown.

Retrieving Relationships

Relationships can be used in two ways.

The first is as a getter. Calling user.getPosts() will execute the relationship, cache the result, and return it.

var posts = user.getPosts();

For new, unloaded entities, relationship getters do not execute a query. To-one relationships return null or their configured default entity, while collection relationships return an empty collection.

var user = getInstance( "User" );

user.getProfile(); // null
user.getPosts(); // []

You can seed an unloaded relationship directly with retrieveRelationship():

user.retrieveRelationship( "posts", [ draftPost ] );

New entities can also fill relationship structs and entities without persisting the aggregate.

The second is as a relationship. Calling user.posts() returns a Relationship instance to retrieve the posts that can be further constrained. A Relationship is backed by qb as well, so feel free to call any qb method to further constrain the relationship.

var newestPosts = user
    .posts()
    .orderBy( "publishedDate", "desc" )
    .get();

You can also call the other Quick fetch methods: first, firstOrFail, find, findOrFail, and firstWhere are all supported. This is especially useful to constrain the entities available to a user by using the user's relationships:

// This will only find posts the user has written.
var post = user.posts().findOrFail( rc.id );

Assigning a Loaded Relationship

Use assignRelationship when you already have a related value and want the relationship accessor to return it without executing a relationship query. This is especially useful after creating related records:

Pass a Quick entity for a singular relationship and an array for a collection relationship. Assigning a value replaces any previously loaded value and marks the relationship as loaded.

assignRelationship only changes the in-memory entity. It does not save either entity, update foreign keys, attach pivot records, or validate that the value matches the relationship type.

Call clearRelationship( "posts" ) to discard the assigned value and its loaded marker. The next relationship accessor call can then lazy load the relationship normally, when lazy loading is enabled.

You can also use other Quick fetch methods that provide new entities if a related entity is not found, such as firstOrNew, firstOrCreate, findOrNew, and findOrCreate.

You can also get a new unloaded related entity by calling either the newEntity or the fill functions.

After a relationship is lazily or eagerly loaded, Quick can call a relationship-specific method and announce an interception point for each related entity. See quickRelationshipLoaded.

loadRelationship

The code above is a shortcut for calling loadRelationship and get{RelationName} on an entity.

Last updated

Was this helpful?