Last active
April 16, 2024 06:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
Thanks
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
Yes, but here is the official package: it is out now: https://github.com/tightenco/parental