Skip to content

Commit

Permalink
feat: Add support for other Foreign Key for different Models (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
robsonek authored Jul 4, 2024
1 parent a267333 commit e940d82
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,14 @@ public static function createForModel(Model $model, array $replacements = [], $t
/* @var \Overtrue\LaravelVersionable\Versionable|Model $model */
$versionClass = $model->getVersionModel();
$versionConnection = $model->getConnectionName();
$userForeignKeyName = $model->getUserForeignKeyName();

$version = new $versionClass();
$version->setConnection($versionConnection);

$version->versionable_id = $model->getKey();
$version->versionable_type = $model->getMorphClass();
$version->{config('versionable.user_foreign_key')} = $model->getVersionUserId();
$version->{$userForeignKeyName} = $model->getVersionUserId();
$version->contents = $model->getVersionableAttributes($replacements);

if ($time) {
Expand Down
8 changes: 7 additions & 1 deletion src/Versionable.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ trait Versionable
// You can define this variable in class, that used this trait to change Model(table) for versions
// Model MUST extend \Overtrue\LaravelVersionable\Version
//public string $versionModel;
//public string $userForeignKeyName;

public static function bootVersionable(): void
{
Expand Down Expand Up @@ -319,9 +320,14 @@ public function getVersionModel(): string
return $this->versionModel ?? config('versionable.version_model');
}

public function getUserForeignKeyName(): string
{
return $this->userForeignKeyName ?? config('versionable.user_foreign_key');
}

public function getVersionUserId()
{
return auth()->id() ?? $this->getAttribute(\config('versionable.user_foreign_key'));
return $this->getAttribute($this->getUserForeignKeyName()) ?? auth()->id();
}

public function getKeepVersionsCount(): string
Expand Down

0 comments on commit e940d82

Please sign in to comment.