Laravel:如何将主键和外键设置为字符串 [英] Laravel: How to set the Primary Key and Foreign Key to string

查看:138
本文介绍了Laravel:如何将主键和外键设置为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用ID的自动递增,而是使用了32个字符的唯一ID.所以当我创建一个关系和查询时,我得到一个空值,因为我的FK期望int 我的模特

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 int my models

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期望为整数,所以我无法检索用户信息.

the problem is in the second query i could not retrieve the users info because the user.id expecting int.

推荐答案

首先,使用innoDB,您可以毫无问题地创建这些前键

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

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

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

预订

    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();
    });

针对用户

    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');
}

现在,当您搜索

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

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

it must work! i've tested this code.

这篇关于Laravel:如何将主键和外键设置为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆