Using a UUID as primary key with Laravel 5

后端 未结 4 1517
余生分开走
余生分开走 2021-01-03 07:27

I\'m trying to create tables that will have a primary key which is a UUID defined as binary(16) instead of the default auto-incrementing id field.<

相关标签:
4条回答
  • 2021-01-03 07:42

    So, I got the thing working like a charm (not tested unit testing):

    1. class UuidModel extends Eloquent is an older (Laravel 4) construct. We use class UuidModel extends Model in Laravel 5
    2. The solution was to move the

      UuidModel::creating(function ($model) {
          echo "Creating Uuid Model...\n";
          $model->{$model->getKeyName()} = (string)$model->generateNewId();
      });
      

      from AppServiceProvider::boot() to EventServiceProvider::boot(). No other changes were required. Everything worked as expected.

    I still don't know why (2) works in EventServiceProvider and not in AppServiceProvider as explained in the official docs. But judging from the name, that's perhaps the way it was meant to be.

    0 讨论(0)
  • 2021-01-03 07:49

    also try use this package will automatically generate and assign UUID field in your model, also can show and update by UUIDs key.

    https://github.com/EmadAdly/laravel-uuid

    0 讨论(0)
  • 2021-01-03 07:52

    How about this idea for storing a 36chr UUID as Binary(16) :

    IMO there is an advantage in not having Laravel generating the UUID. Namely, if new records (some day in the future) get inserted into the database from outside the application the UUID field is properly populated.

    My suggestion: Create a UUID default value trigger using migrations

    (this trigger makes the DataBase server do the work to generate the UUID each time a new customer is inserted)

    <?php namespace MegaBank\HighInterestLoans\Updates;
        use Illuminate\Database\Schema\Blueprint;
        use Illuminate\Database\Migrations\Migration;
    
    class MigrationTriggerForCustomers extends Migration
    {
    public function up()
        {
        
            DB::unprepared('CREATE TRIGGER before_insert_customers
                          BEFORE INSERT ON    
                        `megabank_highinterestloans_customers` 
                          FOR EACH ROW
                          SET new.uuid = UNHEX(REPLACE(UUID(), "-","");');
        }
    
        public function down()
        {
            DB::unprepared('DROP TRIGGER `before_insert_customers`');
        }
    }
    

    Finally, if you want to get a human-readable version of your UUID just do the following:

    SELECT HEX(UUID) FROM customers;
    

    Anyway, hope this helps someone :-)

    0 讨论(0)
  • 2021-01-03 07:56

    This is a quick solution without using events.

    UUidModel.php

    <?php        namespace App;
    
        use \Illuminate\Database\Eloquent\Model;
    
        use \Illuminate\Database\Eloquent\Builder;
    
        class UuidModel extends Model
    
        {
    
        /**
    
        * Insert the given attributes and set the ID on the model.
    
        *
    
        * @param  \Illuminate\Database\Eloquent\Builder  $query
    
        * @param  array  $attributes
    
        * @return void
    
        */
    
            protected function insertAndSetId(Builder $query, $attributes)
    
            {
                $keyName = $this->getKeyName();
                $id = $attributes[$keyName] = $this->generateNewId();
                $query->insert($attributes);
                $this->setAttribute($keyName, $id);
            }
    
        /**
        * Get a new version 4 (random) UUID.
        */
            public function generateNewId()
            {
                return 'uuid!!' ;// just for test
            }
        }
    ?>
    

    Model Example Car.php

    <?php namespace App;
    
        class Car extends UuidModel {
        }
    
    0 讨论(0)
提交回复
热议问题