Files

58 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2024-08-10 13:30:28 -05:00
<?php
2025-01-28 17:33:54 -06:00
declare(strict_types=1);
2025-01-28 17:14:49 -06:00
namespace App\Traits;
2024-08-10 13:30:28 -05:00
trait HasCompositePrimaryKey
{
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return false;
}
/**
* Set the keys for a save update query.
*
2025-01-28 17:14:49 -06:00
* @param \Illuminate\Database\Eloquent\Builder $query
2024-08-10 13:30:28 -05:00
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery($query)
{
foreach ($this->getKeyName() as $key) {
// UPDATE: Added isset() per devflow's comment.
2025-01-28 17:14:49 -06:00
if (isset($this->$key)) {
2024-08-10 13:30:28 -05:00
$query->where($key, '=', $this->$key);
2025-01-28 17:14:49 -06:00
} else {
throw new \Exception(__METHOD__.'Missing part of the primary key: '.$key);
}
2024-08-10 13:30:28 -05:00
}
return $query;
}
// UPDATE: From jessedp. See his edit, below.
/**
* Execute a query for a single record by ID.
*
2025-01-28 17:14:49 -06:00
* @param array $ids Array of keys, like [column => value].
2024-08-10 13:30:28 -05:00
* @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]);
}
2025-01-28 17:14:49 -06:00
2024-08-10 13:30:28 -05:00
return $query->first($columns);
}
2025-01-28 17:14:49 -06:00
}