Skip to content

#[BelongsTo] attribute ignored when property name contains "metadata" (or other Latin words) #2086

@laylatichy

Description

@laylatichy

Tempest version

3.7

PHP version

8.5

Operating system

macOS

Description

ModelInspector::getBelongsTo() singularizes the property name before checking for
#[BelongsTo]. So $product_metadata becomes product_metadatum, no property found,
attribute never seen. The FK isn't extracted — the whole model gets serialized into the
column instead.

class ProductMetadataLink implements Model {
    use IsDatabaseModel;

    public function __construct(
        public Product $product,
        #[BelongsTo]
        public ProductMetadata $product_metadata, // "metadata" singularizes to "metadatum"
        public string $value,
    ) {}
}
(new ProductMetadataLink(...))->save(); // FK not resolved

Same bug in getHasOne() and getHasOneThrough() — all three recurse with the
singularized name without checking the original property first. getHasMany() and
getBelongsToMany() don't singularize so they're fine.

Fix — check original property for explicit attribute before recursing in all three methods:

// getBelongsTo() ~line 197
if (! $singularizedName->equals($name)) {
    if ($this->reflector->hasProperty($name)) {
        if ($this->reflector->hasProperty($name) && $this->reflector->getProperty($name)->hasAttribute(BelongsTo::class) {
             return $this->reflector->getProperty($name)->getAttribute(BelongsTo::class);
         }
    }
    return $this->getBelongsTo($singularizedName);
}

// Same pattern for getHasOne() (~line 265, check HasOne::class)
// Same pattern for getHasOneThrough() (~line 344, check HasOneThrough::class)

I'll handle the fix and open a PR when i wake up just so I remember about it, unless somebody else finds time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions