php - Laravel / MySql Unique String Based On Id? -
i have following migration create mysql database table
public function up() { schema::create('project_auth_keys', function (blueprint $table) { $table->increments('id'); $table->integer('project_id')->unsigned(); $table->string('key', 800); $table->string('first_name', 80); $table->string('last_name', 80); $table->timestamps(); // link project id real project id $table->foreign('project_id')->references('id')->on('projects'); }); }
now want ot accomplish make 'key' "unique"... know can changing
$table->string('key', 800)->unique();
but don't want make unique whole table want make unique based on project_id.
for example entry project_id of 1 , entry project_id of 2 can have same key, there cannot 2 same keys in same project_id.
is can within mysql or have make rule within controller? can in controller not problem, rather in database if possible.
edit
tried adding
$table->primary(array('project_id', 'key'));
added right below $table->primary(array('project_id', 'key'));
however after doing getting error when trying run migration.
something this?
$table->primary(array('project_id', 'key'));
you can find same in documentation here.
solution 1: since have increment column defined, taking same default primary key.
to use composite primary key, can either remove column or calculate column differently, otherwise throw duplicate primary key exception.
also, limitation of length of primary key "767" , hence should reduce key length lower if possible.
i tried following , works:
schema::create('test', function(blueprint $table) { $table->integer('project_id')->unsigned(); $table->string('key', 100); // make sure key length within sql standards(767), "800" not acceptable primary key $table->string('first_name', 80); $table->string('last_name', 80); $table->timestamps(); // add primary $table->primary( array( 'key', 'project_id' ) ); });
solution 2: can perform validation in controller, gives more flexibility believe , have same structure, id primary key. however, not confident performance. have check on that.
hope helps.
Comments
Post a Comment