diff --git a/models/BaseEntity.cfc b/models/BaseEntity.cfc index a3f7a943..a37d7b74 100644 --- a/models/BaseEntity.cfc +++ b/models/BaseEntity.cfc @@ -1335,6 +1335,39 @@ component accessors="true" { return newEntity().fill( arguments.attributes, arguments.ignoreNonExistentAttributes ).save( arguments.options ); } + /** + * Creates new entities for each provided attribute struct and returns them in + * the entity's configured collection type. + * + * Each entity is saved independently so casts, generated keys, timestamps, + * and entity lifecycle events behave the same as they do for `create`. + * + * @attributes An array of attribute structs. + * @ignoreNonExistentAttributes If true, skips attributes that do not exist. + * @options Any options to pass to `queryExecute`. Default: {}. + * + * @throws QuickReadOnlyException + * + * @return array of quick.models.BaseEntity + */ + public any function createAll( + array attributes = [], + boolean ignoreNonExistentAttributes = false, + struct options = {} + ) { + var ignoreAttributes = arguments.ignoreNonExistentAttributes; + var queryOptions = arguments.options; + return newCollection( + arguments.attributes.map( function( entityAttributes ) { + return create( + attributes = entityAttributes, + ignoreNonExistentAttributes = ignoreAttributes, + options = queryOptions + ); + } ) + ); + } + /*===================================== = Relationships = =====================================*/ diff --git a/tests/specs/integration/BaseEntity/CreateSpec.cfc b/tests/specs/integration/BaseEntity/CreateSpec.cfc index 5b1c7b32..e294a3cc 100644 --- a/tests/specs/integration/BaseEntity/CreateSpec.cfc +++ b/tests/specs/integration/BaseEntity/CreateSpec.cfc @@ -48,6 +48,33 @@ component extends="tests.resources.ModuleIntegrationSpec" { expect( newTheme.isNullAttribute( "config" ) ).toBeFalse(); expect( newTheme.getConfig() ).toBe( { "message" : "I should be cast to JSON" } ); } ); + + it( "can create and return multiple entities", function() { + var users = getInstance( "User" ).createAll( [ + { + "username" : "first-new-user", + "firstName" : "First", + "lastName" : "User" + }, + { + "username" : "second-new-user", + "firstName" : "Second", + "lastName" : "User" + } + ] ); + + expect( users ).toBeArray(); + expect( users ).toHaveLength( 2 ); + expect( users[ 1 ].isLoaded() ).toBeTrue(); + expect( users[ 1 ].getId() ).notToBeNull(); + expect( users[ 1 ].getFirstName() ).toBe( "First" ); + expect( users[ 2 ].isLoaded() ).toBeTrue(); + expect( users[ 2 ].getId() ).notToBeNull(); + expect( users[ 2 ].getFirstName() ).toBe( "Second" ); + expect( getInstance( "User" ).whereIn( "username", [ "first-new-user", "second-new-user" ] ).count() ).toBe( + 2 + ); + } ); } ); }