coldbox-modules / quick

A ColdBox ORM Engine
https://quick.ortusbooks.com
MIT License
23 stars 19 forks source link

Idea/Improvement: Return Null When Requesting Relationship Data from Non Loaded Entities #177

Open homestar9 opened 2 years ago

homestar9 commented 2 years ago

Related to this post on the Ortus community forums.

It would be great if, when requesting relationship data from a non-loaded (new) entity, Quick would return null (or an empty array where appropriate) just like if you performed the same operation from a loaded entity. This behavior should be more intuitive and also better follows the null object pattern.

Here's a simple example of how one might use this new change in Quick:

// Post.cfc
component 
    extends="quick.models.BaseEntity" 
    accessors="true" 
{

    // Post belongs to an Author
    function author() {
        return belongsTo( "User" );
    }

}

// Posts.cfc Handler
function index( event, rc, prc ) {

    // Get an existing entity, or return a new one if not found
    prc.post = getInstance( "Post" )
        .firstOrCreate( rc.id );

    // return the memento with the author (it will either be null or populated)
    return prc.post.getMemento( "author" );

}
bdw429s commented 2 years ago

This issue has been mentioned on Ortus Solutions Community. There might be relevant details there:

https://community.ortussolutions.com/t/quick-4-2-4-this-instance-is-not-loaded-so-it-cannot-access-the-relationship/9216/1

homestar9 commented 2 years ago

One way to enable this behavior would be to make the following code changes:

BaseEntity.cfc

  1. Remove calls to guardAgainstNotLoaded() in relationship calls like in belongsTo()
  2. Add the following to isNullValue()
    if ( !arguments.keyExists( "value" ) ) {
     return true;
    }

I'm coming from a place of not being very familiar with Quick, but based on some "hack and slash" experiments, this change appears to work.

homestar9 commented 2 years ago

@elpete Submitted a pull request for your review. https://github.com/coldbox-modules/quick/pull/178

Please be gentle, this is my first Quick PR. ;)