Skip to content

Nested belongsTo relationship #8

@johnwilhite

Description

@johnwilhite

This is a similar issue to #5.

The trait is failing on the following example:

$contract = new Contract([
    'price' => '12',
    'customer' => [ // belongsTo relation
            'name' => 'First Last',
            'reference' => [ // hasMany relation
                [
                    'name' => 'First Last'
                ]
            ]
        ]
    ]
]);

The fillBelongsToRelation save for customer fails with the following, because it's trying to select reference, which is the relation and not a column, from the customers table.

Column not found: 1054 Unknown column 'reference' in 'where clause' 

The following seems to fix the issue for belongsTo relations, it's extracting the relations out and only using the attributes in that lookup.

    /**
     * @param BelongsTo $relation
     * @param array|Model $attributes
     */
    public function fillBelongsToRelation(BelongsTo $relation, $attributes, $relationName)
    {
        $entity = $attributes;
        if (!$attributes instanceof Model) {
            if (method_exists($relation->getRelated(), 'extractFillableRelations')) {
                list($relations, $attributes) = $relation->getRelated()->extractFillableRelations($attributes);
            }

            $entity = $relation->getRelated()
                ->where($attributes)->firstOrFail();
        }
        $relation->associate($entity);
    }

Would this be an appropriate fix? Also I haven't tested the belongs to many, but I'd imagine it would need a similar fix.

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