Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Last active April 16, 2024 06:26
Show Gist options
  • Save calebporzio/a63b165b500d491a0c250eb5853e5d94 to your computer and use it in GitHub Desktop.
Save calebporzio/a63b165b500d491a0c250eb5853e5d94 to your computer and use it in GitHub Desktop.
A model trait that allows child models to use parent table names and relationship keys.
<?php
namespace App\Abilities;
use Illuminate\Support\Str;
use ReflectionClass;
/**
* Note: This is a preview of an upcoming package from Tighten.
**/
trait HasParentModel
{
public function getParentClass()
{
static $parentClassName;
return $parentClassName ?: $parentClassName = (new ReflectionClass($this))->getParentClass()->getName();
}
public function getTable()
{
if (! isset($this->table)) {
return str_replace('\\', '', Str::snake(Str::plural(class_basename($this->getParentClass()))));
}
return $this->table;
}
public function getForeignKey()
{
return Str::snake(class_basename($this->getParentClass())).'_'.$this->primaryKey;
}
public function joiningTable($related)
{
$models = [
Str::snake(class_basename($related)),
Str::snake(class_basename($this->getParentClass())),
];
sort($models);
return strtolower(implode('_', $models));
}
}
@deleugpn
Copy link

deleugpn commented Sep 9, 2017

You rock, man. Anxiously waiting to see this package.

@tucq88
Copy link

tucq88 commented Sep 13, 2017

Awesome! Much convenient on real-life problem. Can't wait until it released.

@ahsankhatri
Copy link

Excellent approach. Waiting for final release.

@Shigeki1120
Copy link

Shigeki1120 commented Oct 5, 2017

When is the package gonna be released? I am dying to use it ;)

@macwinnie
Copy link

Do you have any news about a releasing date? =)

@bleuscyther
Copy link

@calebporzio
Copy link
Author

Yes, but here is the official package: it is out now: https://github.com/tightenco/parental

@DInnaD
Copy link

DInnaD commented Oct 22, 2019

Thanks

@DInnaD
Copy link

DInnaD commented Oct 22, 2019

I got thislink from https://m.habr.com/ru/post/344728/ and I dont understand getName(){which things must be here?}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment