Skip to content

Loading hasMany relationship eagerly loads inverse belongsTo unexpectedly #1942

Description

@nunntom

Tempest version

2.14

PHP version

8.4

Operating system

Linux

Description

When loading a model with a HasMany relationship where the related model defines a BelongsTo relation back to the initial model, the inverse BelongsTo relation model is eagerly loaded, even if not explicitly loaded. Adding #[Lazy] has no effect on this.

This does not cause an issue in itself, but it is not possible to return the resulting model as a JSON response due to infinite recursion.

Steps to reproduce

final class Chicken
{
    use IsDatabaseModel;

    public string $name;

    #[HasMany]
    /** @var \Models\Egg[] */
    public array $eggs;
}

final class Egg
{
    use IsDatabaseModel;

    public int $size;

    #[BelongsTo]
    public Chicken $chicken;
}

$chicken = Chicken::create(
    name: 'Acorn',
);

$egg = Egg::create(
    size: 10,
    chicken: $chicken,
);

$acorn = Chicken::findById($chicken->id)->load('eggs');

$json = json_encode($acorn); // false (JSON_ERROR_RECURSION)

Expectation

I would expect the inverse BelongsTo relation only to be loaded if tagged with #[Eager] or explicitly loaded with load.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions