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

jrs*_*nga 1 laravel laravel-4

我没有使用id的自动增量而是使用32个字符的唯一ID.因此,当我创建一个关系和查询时,我得到一个null因为我的FK期望我的模型

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

class Reservation extend Eloquent {
    public $incrementing = false; 
}
Run Code Online (Sandbox Code Playgroud)

所以当我查询这个

$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);
});
Run Code Online (Sandbox Code Playgroud)

我明白了

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)
}
Run Code Online (Sandbox Code Playgroud)

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

alv*_*pgl 7

在较新版本的 Laravel(我使用 6.5.1)中,您必须将密钥类型设置为字符串(默认 PK 类型设置为整数)

按照问题的例子:

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

class Reservation extend Eloquent {
    public $incrementing = false;
    public $keyType = 'string'; 
}
Run Code Online (Sandbox Code Playgroud)

你可以查看laravel 文档中的示例


ang*_*oru 6

首先,使用innoDB,您可以毫无问题地制作这些外出键

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();
    });
Run Code Online (Sandbox Code Playgroud)

对于用户

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

那么你需要在预订中创建关系

public function user(){
    return $this->belongsTo('User', 'user_id');
}
Run Code Online (Sandbox Code Playgroud)

现在当你搜索

$reservations = Reservation::with('user')->where('user_id', '=', '22beb4892ba944c8b1895855e1d4d1ad')->get();
Run Code Online (Sandbox Code Playgroud)

它必须工作!我已经测试了这段代码.