2014-03-27 55 views
1

我没有使用自动增量的ID,而是使用32个字符的唯一ID。所以,当我创建一个关系查询,即时得到一个空的,因为我的FK期待INT 我的模型Laravel:如何将主键和外键设置为字符串

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。

回答

3

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

用户

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

,那么你需要创建在保留的关系

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

,现在当你搜索

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

它必须努力!我测试过这个代码。

+0

太棒了!有用!只需要从我的$ this-> belongsTo('User')'中输入第二个参数'user_id'。非常感谢! – jrsalunga