Skip to content

Commit

Permalink
feat(HasMany): Many entities can be saved to a hasMany relationship a…
Browse files Browse the repository at this point in the history
…t once

Passing in an array of entities to a `hasMany` relationships `saveMany` call
will save all of the entities at once.
  • Loading branch information
elpete committed May 3, 2019
1 parent 708506d commit c9f8f47
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
7 changes: 7 additions & 0 deletions models/Relationships/HasOneOrMany.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ component extends="quick.models.Relationships.BaseRelationship" accessors="true"
return variables.parent.retrieveAttribute( variables.localKey );
}

function saveMany( entities ) {
arguments.entities = isArray( entities ) ? entities : [ entities ];
return entities.map( function( entity ) {
return save( entity );
} );
}

function save( entity ) {
setForeignAttributesForCreate( entity );
return entity.save();
Expand Down
18 changes: 18 additions & 0 deletions tests/specs/integration/BaseEntity/Relationships/HasManySpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,24 @@ component extends="tests.resources.ModuleIntegrationSpec" appMapping="/app" {
expect( newPost.isLoaded() ).toBeTrue();
expect( newPost.getAuthor().getId() ).toBe( user.getId() );
} );

it( "can saveMany entities at a time", function() {
var newPostA = getInstance( "Post" );
newPostA.setBody( "A new post by me!" );
expect( newPostA.isLoaded() ).toBeFalse();

var newPostB = getInstance( "Post" );
newPostB.setBody( "Another new post by me!" );
expect( newPostB.isLoaded() ).toBeFalse();

var user = getInstance( "User" ).find( 1 );
var posts = user.posts().saveMany( [ newPostA, newPostB ] );

expect( posts[ 1 ].isLoaded() ).toBeTrue();
expect( posts[ 1 ].getAuthor().getId() ).toBe( user.getId() );

expect( posts[ 2 ].isLoaded() ).toBeTrue();
expect( posts[ 2 ].getAuthor().getId() ).toBe( user.getId() );
} );

it( "can create new related entities directly", function() {
Expand Down

0 comments on commit c9f8f47

Please sign in to comment.