diff --git a/models/Relationships/BelongsToMany.cfc b/models/Relationships/BelongsToMany.cfc index be70d11..7bf587c 100644 --- a/models/Relationships/BelongsToMany.cfc +++ b/models/Relationships/BelongsToMany.cfc @@ -649,6 +649,31 @@ component return find( ".", arguments.column ) ? arguments.column : "#listLast( variables.table, " " )#.#arguments.column#"; } + /** + * Creates a new related entity and attaches it to the parent through the pivot table. + * + * @attributes Attributes for the related entity. + * @pivotAttributes Additional attributes for the pivot row. + * @ignoreNonExistentAttributes Whether to ignore attributes not defined on the related entity. + * @options Options passed to the related entity save query. + * + * @return quick.models.BaseEntity + */ + public any function create( + struct attributes = {}, + struct pivotAttributes = {}, + boolean ignoreNonExistentAttributes = false, + struct options = {} + ) { + var entity = variables.related.create( + arguments.attributes, + arguments.ignoreNonExistentAttributes, + arguments.options + ); + attach( entity, arguments.pivotAttributes ); + return entity; + } + /** * Associates one or more ids of the related entity to the parent entity. * diff --git a/tests/specs/integration/BaseEntity/Relationships/BelongsToManySpec.cfc b/tests/specs/integration/BaseEntity/Relationships/BelongsToManySpec.cfc index 774ad4a..7254365 100644 --- a/tests/specs/integration/BaseEntity/Relationships/BelongsToManySpec.cfc +++ b/tests/specs/integration/BaseEntity/Relationships/BelongsToManySpec.cfc @@ -162,6 +162,26 @@ component extends="tests.resources.ModuleIntegrationSpec" { expect( pivot.getCreated_date() ).notToBeNull(); expect( pivot.getModified_date() ).notToBeNull(); } ); + + it( "creates and attaches a related entity", function() { + var post = getInstance( "Post" ).findOrFail( 1245 ); + var tag = post + .tagsWithPivot() + .create( + { "name" : "testing" }, + { + "context" : "created through relationship", + "active" : true + } + ); + + expect( tag ).toBeInstanceOf( "Tag" ); + expect( tag.isLoaded() ).toBeTrue(); + + var attached = post.tagsWithPivot().findOrFail( tag.getId() ); + expect( attached.getPivot().getContext() ).toBe( "created through relationship" ); + expect( attached.getPivot().getActive() ).toBeTrue(); + } ); } ); }