Created
September 10, 2019 08:51
-
-
Save schnabear/afaa7bd984f6ba827036ba839041a590 to your computer and use it in GitHub Desktop.
Laravel Composite Key Trait
This file contains hidden or 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\Models\Traits; | |
| use Illuminate\Database\Eloquent\Builder; | |
| trait CompositeKey | |
| { | |
| /** | |
| * Get the value indicating whether the IDs are incrementing. | |
| * | |
| * @return bool | |
| */ | |
| public function getIncrementing() | |
| { | |
| return false; | |
| } | |
| /** | |
| * Set the keys for a save update query. | |
| * | |
| * @param \Illuminate\Database\Eloquent\Builder $query | |
| * @return \Illuminate\Database\Eloquent\Builder | |
| */ | |
| protected function setKeysForSaveQuery(Builder $query) | |
| { | |
| $keys = $this->getKeyName(); | |
| if(!is_array($keys)){ | |
| return parent::setKeysForSaveQuery($query); | |
| } | |
| foreach($keys as $keyName){ | |
| $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName)); | |
| } | |
| return $query; | |
| } | |
| /** | |
| * Get the primary key value for a save query. | |
| * | |
| * @param mixed $keyName | |
| * @return mixed | |
| */ | |
| protected function getKeyForSaveQuery($keyName = null) | |
| { | |
| if(is_null($keyName)){ | |
| $keyName = $this->getKeyName(); | |
| } | |
| if (isset($this->original[$keyName])) { | |
| return $this->original[$keyName]; | |
| } | |
| return $this->getAttribute($keyName); | |
| } | |
| /** | |
| * Execute a query for a single record by ID. | |
| * | |
| * @param array $ids Array of keys, like [column => value]. | |
| * @param array $columns | |
| * @return mixed|static | |
| */ | |
| public static function find($ids, $columns = ['*']) | |
| { | |
| $me = new self; | |
| $query = $me->newQuery(); | |
| foreach ($me->getKeyName() as $key) { | |
| $query->where($key, '=', $ids[$key]); | |
| } | |
| return $query->first($columns); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment