From c9f8f4773bea5c7bd7e1ae142c5aad0550614aa5 Mon Sep 17 00:00:00 2001 From: Eric Peterson Date: Fri, 3 May 2019 13:18:40 -0500 Subject: [PATCH] feat(HasMany): Many entities can be saved to a hasMany relationship at once Passing in an array of entities to a `hasMany` relationships `saveMany` call will save all of the entities at once. --- models/Relationships/HasOneOrMany.cfc | 7 +++++++ .../BaseEntity/Relationships/HasManySpec.cfc | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/models/Relationships/HasOneOrMany.cfc b/models/Relationships/HasOneOrMany.cfc index 5127a1e2..a25fe3aa 100644 --- a/models/Relationships/HasOneOrMany.cfc +++ b/models/Relationships/HasOneOrMany.cfc @@ -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(); diff --git a/tests/specs/integration/BaseEntity/Relationships/HasManySpec.cfc b/tests/specs/integration/BaseEntity/Relationships/HasManySpec.cfc index a12f87b9..be58fbaf 100644 --- a/tests/specs/integration/BaseEntity/Relationships/HasManySpec.cfc +++ b/tests/specs/integration/BaseEntity/Relationships/HasManySpec.cfc @@ -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() {