framework icon indicating copy to clipboard operation
framework copied to clipboard

Parent class's primary key might be missing in relation methods

Open nandi95 opened this issue 2 years ago • 0 comments

Search terms relations parent child sub class belongsToMany hasOne hasMany morphMany morphOne

Is your feature request related to a problem? Please describe. When using belongsToMany, hasOne, hasMany, morphMany, morphOne relation methods on a new instance. That instance might not have the primary key which is accessed druing the above methods.

Describe the solution you'd like There should be a way to warn the user if the above happens so they become aware when testing their code and have done this mistake.

Describe how this would benefit the project/others It would make the developer's projects less error prone.

Describe alternatives you've considered Workaround is not use the relations without the foreign key missing

Additional context Considered adding the following

/**
 * Throw an error if the current model doesn't have the primary key set.
 *
 * @param {Model} relation
 *
 * @private
 */
private throwIfAncestorDoesntExists(relation: Model & { _relationType: Relation }): void {
    if ((this as unknown as Model).getKey() === undefined) {
        throw new LogicException(
            'Attempted to use ' + relation._relationType + ' relation method to access the \''
            + relation.getName() + '\' model when \''
            + (this as unknown as Model).getName() + '\' does not have the primary key set.'
        );
    }
}

and calling it in the above methods after configureRelationType has been called, but this isn't compatible with the relationDefined because that calls the relation to ensure correct value has been returned.

nandi95 avatar Jan 26 '22 09:01 nandi95