From 249c054daea208753358201cfdfba3f070c510b3 Mon Sep 17 00:00:00 2001 From: Ramesh Kithsiri Date: Tue, 26 Mar 2019 09:22:24 +0530 Subject: [PATCH] Can use composite or single primary keys --- src/Model/Traits/HasCompositePrimaryKey.php | 22 +++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/Model/Traits/HasCompositePrimaryKey.php b/src/Model/Traits/HasCompositePrimaryKey.php index 3853378..50db3ce 100644 --- a/src/Model/Traits/HasCompositePrimaryKey.php +++ b/src/Model/Traits/HasCompositePrimaryKey.php @@ -14,9 +14,23 @@ trait HasCompositePrimaryKey */ public function getIncrementing() { - return false; + return (is_array($this->getKeyName()))?$this->incrementing:false; } + /** + * Returning the key names for the model + * + * @return string[] + */ + public function getKeyNames(){ + $keys = $this->getKeyName(); + if(!is_array($keys)){ + if($keys) + $keys = [$keys]; + } + + return $keys; + } /** * Get the value of the model's primary key. * @@ -26,7 +40,7 @@ public function getKey() { $attributes = []; - foreach ($this->getKeyName() as $key) { + foreach ($this->getKeyNames() as $key) { $attributes[$key] = $this->getAttribute($key); } @@ -41,7 +55,7 @@ public function getKey() */ protected function setKeysForSaveQuery(Builder $query) { - foreach ($this->getKeyName() as $key) { + foreach ($this->getKeyNames() as $key) { if (isset($this->$key)) $query->where($key, '=', $this->$key); else @@ -63,7 +77,7 @@ public static function find($ids, $columns = ['*']) $me = new self; $query = $me->newQuery(); - foreach ($me->getKeyName() as $key) { + foreach ($me->getKeyNames() as $key) { $query->where($key, '=', $ids[$key]); }