Skip to content

Composite foreign keys #32

@TheLevti

Description

@TheLevti

The issue

This trait is currently missing support for foreign keys that consist out of multiple columns.

The cause

The suspected line of code is at line 133:

$isMissingBelongsToFK = $association instanceof BelongsTo && !isset($this->_fields[$association->getForeignKey()]);

The code fails to check the return type of the getForeignKey() call, which is defined as string|string[]. If the foreign key is defined as an array of columns, the trait will fail with:

Response: {\n
    "message": "Illegal offset type in isset or empty",\n
    "exception": "TypeError",\n
    "file": "/var/www/html/vendor/jeremyharris/cakephp-lazyload/src/ORM/LazyLoadEntityTrait.php",\n
    "line": 133,\n
    "trace": [\n
        {\n
            "file": "/var/www/html/vendor/jeremyharris/cakephp-lazyload/src/ORM/LazyLoadEntityTrait.php",\n
            "line": 39,\n
            "function": "_lazyLoad",\n
            "class": "App\\Model\\Entity\\MyModel",\n
            "type": "->"\n
        },\n
        {\n
            "file": "/var/www/html/vendor/cakephp/cakephp/src/Datasource/EntityTrait.php",\n
            "line": 129,\n
            "function": "get",\n
            "class": "App\\Model\\Entity\\MyModel",\n
            "type": "->"\n
        },\n
...

What happens here is that you try to access an array index of type array, which can't work.

The solution

$isMissingBelongsToFK = false;
if ($association instanceof BelongsTo) {
    $foreignKeys = $association->getForeignKey();
    if (is_array($foreignKeys)) {
        foreach ($foreignKeys as $foreignKey) {
            if (!isset($this->_fields[$foreignKey])) {
                $isMissingBelongsToFK = true;
                break;
            }
        }
    } else {
        $isMissingBelongsToFK = !isset($this->_fields[$foreignKeys]);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions