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

后端 未结 2 401
野趣味
野趣味 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: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.

提交回复
热议问题