Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - how to use foreign primary key that's not an integer?

Tags:

mysql

laravel

I'm trying to set a string column as a primary key of a table, then reference that from another table as a foreign key. Is this possible? Per the documentation:

Laravel assumes every table has a numeric primary key (usually named “id”) and ensures the value of this column is unique for each new row added to the table. Laravel doesn’t really work well unless each table has a numeric primary key. So, for your average Laravel application, please ensure that you define a primary key using the increments() method.

In my case, I don't want to define an id column as it would be useless. The string column I want to define will act as a primary key. If this is possible, can I get an example migration snippet?

like image 888
StackOverflowNewbie Avatar asked Jul 24 '14 22:07

StackOverflowNewbie


People also ask

Can you foreign key a non primary key?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.

Why foreign keys are not redundant?

Essentially, primary and foreign keys are used as a way to constrain or link related data in a database. This ensures that data remains consistent and that the database contains no redundant data. For example, if you delete a table (or even a row in a table) that other tables rely on, the redundant data is removed.

How do I change the default primary key in laravel?

By default, eloquent assume that each model has a primary key column named id. But if you need to change the primary key with your own custom column name you can change it using the protected $primaryKey a property on your model.

What is primary key in laravel?

By default, Eloquent models expect for the primary key to be named 'id' . If that is not your case, you can change the name of your primary key by specifying the $primaryKey property.


1 Answers

This is an old question, but for the sake of correctness I'd like to point out that in the current versions of Eloquent you can indeed use non numeric primary/foreign keys.

One thing you need to do is to set the property $incrementing to false on the models that use non autoincrementing ids.

class Employee extends Model
{
    public $incrementing = false;

    // ...
}

also, the migration can be something like this:

Schema::create('employees', function (Blueprint $table) {
    $table->string('id')->primary();
    // ...
});
like image 104
Bogdan Avatar answered Oct 02 '22 13:10

Bogdan