Laravel: How to set the Primary Key and Foreign Key to string

后端 未结 2 399
野趣味
野趣味 2020-12-21 13:19

I\'m not using the auto increment for the id instead i\'m using the 32 char unique id. So when i create a relationship and query, im getting a null because my FK expecting i

相关标签:
2条回答
  • 2020-12-21 13:26

    In newer versions of Laravel (Im using 6.5.1) you have to set up the key type to string (By default PK type is set to integer)

    Following the example of the question:

    class User extend Eloquent {
        public $incrementing = false; 
        public $keyType = 'string';
    }
    
    class Reservation extend Eloquent {
        public $incrementing = false;
        public $keyType = 'string'; 
    }
    

    You can see the example in the laravel documentation

    0 讨论(0)
  • 2020-12-21 13:36

    First, with innoDB you could make those foreing keys without problem

    InnoDB allows a foreign key constraint to reference a non-unique key. This is an InnoDB extension to standard SQL.

    Mabe you have your tables wrong, try this

    For Reservations

        Schema::create('reservations', function($table)
        {
            $table->engine = 'InnoDB';
            $table->string('id', 32)->index();
            $table->string('name', 128);
            $table->string('user_id', 32)->references('id')->on('users');
            $table->timestamps();
        });
    

    for users

        Schema::create('users', function($table)
        {
            $table->engine = 'InnoDB';
            $table->string('id', 32)->index();
            $table->string('name', 128);
            $table->timestamps();
        });
    

    then you need to create the relationship in reservations

    public function user(){
        return $this->belongsTo('User', 'user_id');
    }
    

    and now when you search

    $reservations = Reservation::with('user')->where('user_id', '=', '22beb4892ba944c8b1895855e1d4d1ad')->get();
    

    it must work! i've tested this code.

    0 讨论(0)
提交回复
热议问题