Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zendzo/4708e2be75e8be4b629b2cc1ed704f26 to your computer and use it in GitHub Desktop.
Save zendzo/4708e2be75e8be4b629b2cc1ed704f26 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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment