eloquent-versioning icon indicating copy to clipboard operation
eloquent-versioning copied to clipboard

how to define relations

Open jelmerbou opened this issue 6 years ago • 2 comments

I have one product model with versioned data and I got a category model that has one or many products. When i want to delete a category it has to check if there are products related to the category. How to define the relation that it goes to the products_version table to check if the category_id exists here before deleting it?

jelmerbou avatar Apr 04 '18 12:04 jelmerbou

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.category_id' in 'where clause' (SQL: select categories.*, (select count(*) from productsinner joinproducts_versiononproducts.id=products_version.ref_idandproducts_version.version=products.latest_versionwherecategories.id=products.category_idandproducts_version.deleted_atis null) asproducts_countfromcategorieswhereid = 1 limit 1)

jelmerbou avatar Apr 04 '18 12:04 jelmerbou

Hi there,

It does indeed appear that certain relations don't work. Fortunately I did just get hasMany relation working locally. I'm going to fix all relations, and put them under tests before committing them here.

For now you can use this hot fix on the model that has the hasMany relation, and replace it with hasManyVersioned.

trait HasVersionedRelationshipsTrait
{
    public function hasManyVersioned($related, $foreignKey = null, $localKey = null)
    {
        $instance = $this->newRelatedInstance($related);

        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $localKey = $localKey ?: $this->getKeyName();

        return $this->newHasMany(
            $instance->newQuery(), $this, $instance->getVersionTable().'.'.$foreignKey, $localKey
        );
    }
}

crashkonijn avatar May 23 '18 21:05 crashkonijn