https://github.com/laravel/framework/issues/5517
Eloquent doesn't support composite keys
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 ?
https://github.com/laravel/framework/issues/5517
Eloquent doesn't support composite keys
You can define in your migration table as well,
$table->string('Military_No')->primary();
$table->string('classification_code')->primary();
Yeah, in the migration because the database supports it. But you can't use it in Eloquent models because Eloquent doesn't support it.
so i can't use laravel relationship with this model, right ?
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'
);
}
@pciranda Thank you i will try this :)
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;
It's worth checking out the thiagoprz/eloquent-composite-key package which extends Eloquent with composite key support.
Please or to participate in this conversation.