Laravel:如何将主键和外键设置为字符串

Laravel:如何将主键和外键设置为字符串,laravel,laravel-4,Laravel,Laravel 4,我没有对id使用自动递增,而是使用32个字符的唯一id。因此,当我创建关系和查询时,我得到一个null,因为我的FK需要int 我的模型 class User extend Eloquent { public $incrementing = false; } class Reservation extend Eloquent { public $incrementing = false; } 所以当我问这个问题时 $reservations = Reservation::

我没有对id使用自动递增,而是使用32个字符的唯一id。因此,当我创建关系和查询时,我得到一个null,因为我的FK需要int 我的模型

class User extend Eloquent {
    public $incrementing = false; 
}

class Reservation extend Eloquent {
    public $incrementing = false; 
}
所以当我问这个问题时

$reservations = Reservation::with('user')->where('user_id', '=', '22beb4892ba944c8b1895855e1d4d1ad')->get();
i could not retrieve the users information but the reservations info is working fine
when i try to listen for query. eg:
Event::listen('illuminate.query', function($query, $bindings, $time, $name){
    var_dump($query);
    var_dump($bindings);
});
我明白了

string(46) "select * from `reservation` where `user_id` = ?"
array(1) {
  [0]=>
  string(36) "22beb4892ba944c8b1895855e1d4d1ad"
}
string(53) "select * from `user` where `user`.`id` in (?)"
array(1) {
  [0]=>
  int(0)
}

问题是在第二个查询中,我无法检索用户信息,因为user.id需要int.

首先,使用innoDB,您可以毫无问题地生成这些foreing键

InnoDB允许外键约束引用非唯一键。 这是标准SQL的InnoDB扩展

也许你的桌子弄错了,试试这个

预订

    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();
    });
public function user(){
    return $this->belongsTo('User', 'user_id');
}
对于用户

    Schema::create('users', function($table)
    {
        $table->engine = 'InnoDB';
        $table->string('id', 32)->index();
        $table->string('name', 128);
        $table->timestamps();
    });
然后您需要在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();
    });
public function user(){
    return $this->belongsTo('User', 'user_id');
}
现在当你搜索的时候

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

它一定有用!我已经测试过这段代码。

在较新版本的Laravel(我使用6.5.1)中,您必须将密钥类型设置为string(默认情况下,PK类型设置为integer)

以问题为例:

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

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

你可以在

中看到这个例子,太棒了!它起作用了!只需在my
$this->belongsTo('user')
中设置第二个参数
用户id
。谢谢!