michaeldyrynda / laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models
MIT License
442 stars 46 forks source link

What would be the best way to use UUID in MYSQL #88

Closed shenjiayu closed 4 years ago

shenjiayu commented 4 years ago

First of all, thanks for making this handy package.

After done a few researches, I am still confused about how to design the database schema using the UUID as the primary key.

Let's started with an easy example. Two tables: users and posts I would like to have the uuid char(36) in MYSQL as the primary key for both tables, and have the user_id char(36) as the foreign key in the posts table.

I am using this package, so I am sure the uuid generated is already timestamp based already.

Q:

  1. Should I use the uuid as the primary key of both tables?
  2. What exact data type should I use to store uuid?
michaeldyrynda commented 4 years ago

Hey,

I would still use an auto-incrementing integer as the primary key for your tables and do your joins on that. It will be the most optimal way of carrying out your joins. You can read this article, from the readme, for more info.

You can just use Laravel's default for UUID, via the $table->uuid() definition when creating your database migrations. This will create a column of type char(36).

If you want to store them in a more efficient manner (binary(16)), and help with casting between string and binary representations for you.

shenjiayu commented 4 years ago

Thanks for your reply..So all relationships (foreign keys) remain using the auto_increment key internally.

Do you have any clues how I can use the uuid column as the identifier in Nova?

My current workaround would be having the id of UUID type and having another column probably primary_id as the primary key and handle the relations under the hood to avoid being queries by Nova automatically.