dyrynda/eloquent-composite-primary-keys

Offers composite primary keys on Eloquent models

2.0.0 2019-09-28 04:32 UTC

This package is auto-updated.

Last update: 2024-10-28 16:27:48 UTC


README

A single trait to implement in your Eloquent models to support composite primary keys. The Laravel Schema builder supports creating composite primary keys, but Eloquent models don't support it.

This package is largely inspired by suggested code on Stack Exchange and has also been released in a package with more than this functionality. I needed a separate package for just this purpose.

This package has been forked from Coen Jacobs as we have a need for it moving forward (Laravel 6.0+), but they've archived the project.

Install

Install this package through Composer:

composer require dyrynda/eloquent-composite-primary-keys

Make sure you have a database schema that supports composite primary keys, for example via a migration:

Schema::create('products', function (Blueprint $table) {
    $table->integer('first_key');
    $table->integer('another_key');
    $table->primary(['first_key', 'another_key']);
    $table->timestamps();
});

Use the trait on the Eloquent model you wish to have composite primary keys on:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Dyrynda\EloquentCompositePrimaryKeys\HasCompositePrimaryKey;

class Product extends Model
{
	use HasCompositePrimaryKey;

Next, you set the $primaryKey property on your Eloquent model to an array containing the field names that together form your composite primary key:

protected $primaryKey = array('first_key', 'another_key');