2014-03-27 53 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