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
  • Defining
  • Inserting & Updating
  • save
  • create
  • Removing

Was this helpful?

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

hasMany

PrevioushasOneNextbelongsTo

Last updated 7 years ago

Was this helpful?

Defining

A hasMany relationship is a one-to-many relationship. For instance, a User may have multiple Posts.

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

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

}

The first value passed to hasMany 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 hasMany is also .

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

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

}

Inserting & Updating

save

You can call the save method on the relationship passing in an entity to relate.

var post = getInstance( "Post" ).fill( {
    "title" = "My Post",
    "body" = "Hello, world!"
} );

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

user.posts().save( post );

This will add the User entity's id as a foreign key in the Post and save the Post to the database.

Note: the save method is called on the posts relationship, not the getPosts collection.

create

Use the create method to create and save a related entity directly through the relationship.

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

user.posts().create( {
    "title" = "My Post",
    "body" = "Hello, world!"
} );

This example will have the same effect as the previous example.

Removing

There are two ways to add an entity to a hasMany relationship. Both mirror the for entities.

Removing a hasMany relationship is handled in two ways: either by using the dissociate method on the side of the relationship or by deleting the side of the relationship.

belongsTo
insert API
belongsTo
belongsTo