Home > Backend Development > PHP Tutorial > How to Define and Use Composite Primary Keys in Laravel 5 Models?

How to Define and Use Composite Primary Keys in Laravel 5 Models?

Susan Sarandon
Release: 2024-11-30 21:42:14
Original
673 people have browsed it

How to Define and Use Composite Primary Keys in Laravel 5 Models?

How to Define Composite Primary Keys in Laravel 5 Models

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."

Customizing Primary Keys

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.

Using Composite Primary Key Trait

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);
    }
}
Copy after login

Implementing the Trait

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'];

    ...
}
Copy after login

Additional Considerations

  • This approach works well for most use cases.
  • Complex use cases may require custom solutions.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template