I need to create a table with a composite primary key. I considered several solutions to the problem in order to create an AUTO_INCREMENT field along with some other fields and make them a composite primary key, but in the end I managed to do it as follows:
class CreateSpecificationTable extends Migration { public function up() { Schema::create('specification', function(Blueprint $table){ $table->increments('specificationID'); $table->integer('categoryID', false, true); $table->string('name', 100); $table->dateTime('created_at'); $table->dateTime('updated_at')->nullable()->default(null); $table->dateTime('deleted_at')->nullable()->default(null); $table->foreign('categoryID')->references('categoryID')->on('categories'); }); DB::unprepared('ALTER TABLE specification DROP PRIMARY KEY, ADD PRIMARY KEY(specificationID, categoryID, name)'); }
The model for this table is quite simple:
class Specification extends Eloquent { protected $table = 'specification'; protected $primaryKey = array('specificationID', 'categoryID', 'name'); }
Then the seeder looks like this:
class SpecificationSeeder extends Seeder { public function run() { Specification::create(array( 'categoryID'=>1, 'name'=>'size', )); Specification::create(array( 'categoryID'=>2, 'name'=>'resolution', )); Specification::create(array( 'categoryID'=>1, 'naam'=>'connection', )); } }
However, when I run the php artisan db:seed command from CMD, I get the following error:
[ErrorException] PDO::lastInsertId() expects parameter 1 to be string, array given
It is strange that I already created many other tables in this application, but this is the first where protected $primaryKey in the model consists of an array with fields, and not with one primary key.
In addition, despite providing this error, the first "seed" is added to the database, but nothing happens after that.