This repository has been archived on 2024-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
vbbs/app/Traits/HasCompositePrimaryKey.php

53 lines
1.0 KiB
PHP
Raw Permalink Normal View History

2018-12-03 12:59:22 +00:00
<?php
namespace App\Traits;
use \Illuminate\Database\Eloquent\Builder;
/**
* Trait HasCompositePrimaryKey
* Enables primary keys to be an array.
*
* @package App\Traits
*/
trait HasCompositePrimaryKey {
/**
* 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);
}
}