MostafaGamal's avatar

How to define a protected $primaryKey property for composite key

I want to define a protected $primaryKey property for composite keys.

i tried

protected $primaryKey = ['Military_No', 'classification_code'];

but it didn't work ! can any one help ?

0 likes
9 replies
munazzil's avatar

You can define in your migration table as well,

     $table->string('Military_No')->primary();
     $table->string('classification_code')->primary();
ftiersch's avatar

Yeah, in the migration because the database supports it. But you can't use it in Eloquent models because Eloquent doesn't support it.

1 like
MostafaGamal's avatar

so i can't use laravel relationship with this model, right ?

Pciranda's avatar

Try this.

// Migration
$table->string('Military_No')->primary();
$table->string('classification_code')->primary();
$table->string('military_no_classification_code')
    ->virtualAs('concat(Military_No,classification_code)')
    ->index();

// Military Model 
protected $primaryKey = 'military_no_classification_code';

You can change de primaryKey on the fly.

Military::find('xxxxyyyy'); // military_no_classification_code

$military = (new Military)->setKeyName('Military_No');
$military->find('xxxx'); // military_no 

$military = (new military)->setKeyName('classification_code');
$military->find('yyyy'); // classification_code 

Relationships

// App\Military.php
function weaponsByMilitaryNo() {
      return $this->hasMany(App\Weapon::class, 'Military_No', 'Military_No');
}

function weaponsByClassificationCode() {
      return $this->hasMany(App\Weapon::class, 'classification_code', 'classification_code');
}

function weaponsByCompositeKeys() {
      return $this->hasMany(
        App\Weapon::class,
        'military_no_classification_code',
        'military_no_classification_code'
       );
}

6 likes
Snapey's avatar

Not sure why you would need to do this when you can specify the key for route model binding, and you can create a unique index on those two columns.

Anyway, if you are using anything other than incrementing primary key, you need to add to your model

protected $incrementing=false;
1 like

Please or to participate in this conversation.