More components for forms, updated base component, updated CompsiteKeys based on thiagoprz/eloquent-composite-key

This commit is contained in:
2024-07-23 18:47:36 +10:00
parent b9a3cd5647
commit f32c29fa8c
12 changed files with 133 additions and 75 deletions

View File

@@ -25,33 +25,90 @@ trait CompositeKeys {
{
$keys = $this->getKeyName();
if (! is_array($keys)) {
return parent::setKeysForSaveQuery($query);
}
foreach($keys as $keyName) {
$query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
}
return $query;
return !is_array($keys)
? parent::setKeysForSaveQuery($query)
: $query->where(function($q) use($keys) {
foreach ($keys as $key){
$q->where($key,$this->getAttribute($key));
}
});
}
/**
* Get the primary key value for a save query.
* Get the casts array.
*
* @return array
*/
public function getCasts()
{
if ($this->getIncrementing())
return array_merge([$this->getKeyName() => $this->getKeyType()],$this->casts);
return $this->casts;
}
/**
* @return false
*/
public function getIncrementing()
{
return FALSE;
}
/**
* Get the value of the model's primary key.
*
* @param mixed $keyName
* @return mixed
*/
protected function getKeyForSaveQuery($keyName = null)
public function getKey()
{
if (is_null($keyName)) {
$keyName = $this->getKeyName();
}
$fields = $this->getKeyName();
$keys = [];
if (isset($this->original[$keyName])) {
return $this->original[$keyName];
}
array_map(function($key) use(&$keys) {
$keys[] = $this->getAttribute($key);
}, $fields);
return $this->getAttribute($keyName);
return $keys;
}
/**
* Finds model by primary keys
*
* @param array $ids
* @return mixed
*/
public static function find(array $ids)
{
$modelClass = get_called_class();
$model = new $modelClass();
$keys = $model->primaryKey;
return $model->where(function($query) use($ids,$keys) {
foreach ($keys as $idx => $key) {
if (isset($ids[$idx]))
$query->where($key, $ids[$idx]);
else
$query->whereNull($key);
}
})->first();
}
/**
* Find model by primary key or throws ModelNotFoundException
*
* @param array $ids
* @return mixed
*/
public static function findOrFail(array $ids)
{
$modelClass = get_called_class();
$model = new $modelClass();
$record = $model->find($ids);
if (! $record)
throw new ModelNotFoundException;
return $record;
}
}