Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for other Foreign Key for different Models #78

Merged
merged 1 commit into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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