eloquent-versioning
eloquent-versioning copied to clipboard
how to define relations
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?
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.category_id' in 'where clause' (SQL: select
categories.*, (select count(*) from
productsinner join
products_versionon
products.
id=
products_version.
ref_idand
products_version.
version=
products.
latest_versionwhere
categories.
id=
products.
category_idand
products_version.
deleted_atis null) as
products_countfrom
categorieswhere
id = 1 limit 1)
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
);
}
}