Skip to content

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

Open
@nandi95

Description

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.

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthas workaroundThere is a way to achieve the aim

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions