Created
May 17, 2016 13:32
-
-
Save mpociot/121515395d48b0cffcf4ac9ea26683fc to your computer and use it in GitHub Desktop.
Trait for Laravel 5 models that have composite keys.
This file contains 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\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