Skip to content

Instantly share code, notes, and snippets.

@mpociot
Created May 17, 2016 13:32
Show Gist options
  • Save mpociot/121515395d48b0cffcf4ac9ea26683fc to your computer and use it in GitHub Desktop.
Save mpociot/121515395d48b0cffcf4ac9ea26683fc to your computer and use it in GitHub Desktop.
Trait for Laravel 5 models that have composite keys.
<?php
namespace App\Traits;
use Exception;
use Illuminate\Database\Eloquent\Builder;
/**
* Use this trait if your model has a composite primary key.
* The primary key should then be an array with all applicable columns.
*
* Class HasCompositeKey
* @package App\Traits
*/
trait HasCompositeKey
{
/**
* 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 Builder $query
* @return Builder
* @throws Exception
*/
protected function setKeysForSaveQuery(Builder $query)
{
foreach ($this->getKeyName() as $key) {
if ($this->$key)
$query->where($key, '=', $this->$key);
else
throw new Exception(__METHOD__ . 'Missing part of the primary key: ' . $key);
}
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment