In Laravel, tables with multiple primary keys can pose a challenge when modeling them. By default, Laravel models assume a single primary key named "id."
To handle composite primary keys, where multiple columns define table rows uniquely, we need to customize the model. However, using arrays or comma-separated strings to define the primary key doesn't work in Model.php.
A solution to this limitation is using the following trait:
namespace App\Model\Traits; // *** Adjust namespace to match your models *** use Illuminate\Database\Eloquent\Builder; trait HasCompositePrimaryKey { /** * Indicates if IDs are incrementing. * * @return bool */ public function getIncrementing() { return false; // Composite keys are not incrementing. } /** * Set keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected function setKeysForSaveQuery(Builder $query) { foreach ($this->getKeyName() as $key) { // Add if isset() if (isset($this->$key)) { $query->where($key, '=', $this->$key); } else { throw new Exception('Missing part of primary key: ' . $key); } } return $query; } /** * Execute 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); } }
Place the trait in your models' "Traits" directory and add it to any model with composite keys:
class MyModel extends Eloquent { use Traits\HasCompositePrimaryKey; // *** Use the trait *** /** * The primary key of the table. * * @var string */ protected $primaryKey = ['key1', 'key2']; ... }
The above is the detailed content of How to Define and Use Composite Primary Keys in Laravel 5 Models?. For more information, please follow other related articles on the PHP Chinese website!