Skip to content

Commit

Permalink
feat(Relationships): Allow saving of ids as well as entities
Browse files Browse the repository at this point in the history
  • Loading branch information
elpete committed May 3, 2019
1 parent c9f8f47 commit 3f30131
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions models/Relationships/HasOneOrMany.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ component extends="quick.models.Relationships.BaseRelationship" accessors="true"
}

function save( entity ) {
if ( isSimpleValue( entity ) ) {
entity = variables.related
.newEntity()
.set_loaded( true )
.forceAssignAttribute(
variables.related.get_key(),
entity
);
}
setForeignAttributesForCreate( entity );
return entity.save();
}
Expand Down
33 changes: 33 additions & 0 deletions tests/specs/integration/BaseEntity/Relationships/HasManySpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ component extends="tests.resources.ModuleIntegrationSpec" appMapping="/app" {
expect( newPost.getAuthor().getId() ).toBe( user.getId() );
} );

it( "can save an id instead of an entity", function() {
var newPost = getInstance( "Post" );
newPost.setBody( "A new post by me!" );
newPost.save();
expect( newPost.isLoaded() ).toBeTrue();

var user = getInstance( "User" ).find( 1 );
newPost = user.posts().save( newPost.keyValue() );
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!" );
Expand All @@ -38,6 +50,27 @@ component extends="tests.resources.ModuleIntegrationSpec" appMapping="/app" {
expect( posts[ 2 ].getAuthor().getId() ).toBe( user.getId() );
} );

it( "can save many ids at a time", function() {
var newPostA = getInstance( "Post" );
newPostA.setBody( "A new post by me!" );
newPostA.save();
expect( newPostA.isLoaded() ).toBeTrue();

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

var user = getInstance( "User" ).find( 1 );
var posts = user.posts().saveMany( [ newPostA.keyValue(), 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() {
var user = getInstance( "User" ).find( 1 );
expect( user.getPosts() ).toHaveLength( 2 );
Expand Down

0 comments on commit 3f30131

Please sign in to comment.