Added CompositeKeys Traits for Models with multiple primary keys
This commit is contained in:
parent
55cbe4087c
commit
444c159ab9
57
src/Traits/CompositeKeys.php
Normal file
57
src/Traits/CompositeKeys.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Leenooks\Traits;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/**
|
||||
* Trait CompositeKeys
|
||||
* Enable Models to have multiple primary keys
|
||||
*
|
||||
* Need to add to the Model...
|
||||
* public $incrementing = false;
|
||||
* protected $primaryKey = [<ARRAY_OF_KEYS>];
|
||||
*
|
||||
* @package Leenooks\Traits
|
||||
*/
|
||||
trait CompositeKeys {
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user