Skip to content

Instantly share code, notes, and snippets.

@TwilightDuck
Last active September 30, 2020 18:35
Show Gist options
  • Save TwilightDuck/7b9baf37d1605f47f8c8213b66a68b65 to your computer and use it in GitHub Desktop.
Save TwilightDuck/7b9baf37d1605f47f8c8213b66a68b65 to your computer and use it in GitHub Desktop.
Trait that enables a Eloquent model to have Composite Keys.
<?php
namespace App\Traits;
use RuntimeException;
trait HasCompositePrimaryKey
{
public function getIncrementing(): bool
{
return false;
}
protected function setKeysForSaveQuery($query)
{
foreach ($this->getKeyName() as $key) {
if (isset($this->$key)) {
$query->where($key, '=', $this->$key);
}
else {
throw new RuntimeException(__METHOD__ . 'Missing part of the primary key: ' . $key);
}
}
return $query;
}
/**
* Execute a query for a single record by ID.
*
* @param array $ids Array of keys, like [column => value].
* @param array $columns
* @return mixed|static
*/
public static function find($ids, $columns = ['*'])
{
$me = new self;
$query = $me->newQuery();
foreach ($me->getKeyName() as $key) {
$query->where($key, '=', $ids[$key]);
}
return $query->first($columns);
}
/**
* Get an attribute from the model.
*
* @param string|array $key
* @return mixed
*/
public function getAttribute($key)
{
if (!$key || is_array($key)) {
return;
}
// If the attribute exists in the attribute array or has a "get" mutator we will
// get the attribute's value. Otherwise, we will proceed as if the developers
// are asking for a relationship's value. This covers both types of values.
if (array_key_exists($key, $this->attributes) ||
array_key_exists($key, $this->casts) ||
$this->hasGetMutator($key) ||
$this->isClassCastable($key)) {
return $this->getAttributeValue($key);
}
// Here we will determine if the model base class itself contains this given key
// since we don't want to treat any of those methods as relationships because
// they are all intended as helper methods and none of these are relations.
if (method_exists(self::class, $key)) {
return;
}
return $this->getRelationValue($key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment