问题
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;
}
so when i query this
$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);
});
i get this
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)
}
the problem is in the second query i could not retrieve the users info because the user.id expecting int.
回答1:
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.
来源:https://stackoverflow.com/questions/22692054/laravel-how-to-set-the-primary-key-and-foreign-key-to-string