Quick ORM
1.3.0
1.3.0
  • Introduction
  • Getting Started
    • Defining An Entity
    • Retrieving Entities
    • Creating New Entities
    • Updating Existing Entities
    • Deleting Entities
    • Query Scopes
  • Relationships
    • Relationship Types
      • hasOne
      • hasMany
      • belongsTo
      • belongsToMany
      • hasManyThrough
      • polymorphicBelongsTo
      • polymorphicHasMany
    • Retrieving Relationships
    • Eager Loading
  • Collections
  • Custom Getters & Setters
  • Serialization
  • Interception Points
  • Debugging
  • Contributing
Powered by GitBook
On this page
  • Updating
  • Removing

Was this helpful?

Edit on Git
Export as PDF
  1. Relationships
  2. Relationship Types

belongsTo

PrevioushasManyNextbelongsToMany

Last updated 7 years ago

Was this helpful?

A belongsTo relationship is a many-to-one relationship. For instance, a Post may belong to a User.

// Post.cfc
component extends="quick.models.BaseEntity" {

    function user() {
       return belongsTo( "User" );
    }

}

The first value passed to belongsTo is a WireBox mapping to the related entity.

Quick determines the foreign key of the relationship based on the entity name and key values. In this case, the Post entity is assumed to have a userId foreign key. You can override this by passing a foreign key in as the second argument:

return hasMany( "Post", "FK_userID" );

The inverse of belongsTo is or .

// User.cfc
component extends="quick.models.BaseEntity" {

    function posts() {
        return hasMany( "Post" );
    }

    function latestPost() {
        // remember, relationships are just queries!
        return hasOne( "Post" ).orderBy( "createdDate", "desc" );
    }

}

Updating

To update a belongsTo relationship, use the associate method. associate takes the entity to associate as the only argument.

var post = getInstance( "Post" ).findOrFail( 1 );

var user = getInstance( "User" ).findOrFail( 1 );

post.user().associate( user );

post.save();

Note: associate does not automatically save the entity. Make sure to call save when you are ready to persist your changes to the database.

Removing

To remove a belongsTo relationship, use the dissociate method.

var post = getInstance( "Post" ).findOrFail( 1 );

post.user().dissociate()

post.save();

Note: dissociate does not automatically save the entity. Make sure to call save when you are ready to persist your changes to the database.

hasMany
hasOne