Skip to content

Instantly share code, notes, and snippets.

@pedrofmj
Created January 19, 2021 10:09
Show Gist options
  • Save pedrofmj/614061eff182626b7f2056073edc600e to your computer and use it in GitHub Desktop.
Save pedrofmj/614061eff182626b7f2056073edc600e to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
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);
}
public function getKey()
{
$a = [];
for ($i = 0; $i < count($this->primaryKey); $i++) {
$a[] = $this->getAttribute($this->primaryKey[$i]);
}
return $a;
}
/**
* Reload the current model instance with fresh attributes from the database.
*
* @return $this
*/
public function refresh()
{
if (! $this->exists) {
return $this;
}
//$this->setRawAttributes(
// static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes
//);
$keys = $this->getKey();
$q = static::newQueryWithoutScopes();
for ($i = 0; $i < count($this->primaryKey); $i++) {
$q = $q->where($this->primaryKey[$i], $keys[$i]);
}
$o = $q->first();
if ($o == null) {
throw new Exception("Model not found");
}
$this->load(collect($this->relations)->reject(function ($relation) {
return $relation instanceof Pivot
|| (is_object($relation) && in_array(AsPivot::class, class_uses_recursive($relation), true));
})->keys()->all());
$this->syncOriginal();
return $this;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment