2014-09-29 129 views
0

我想用Laravel一對一的關係來實現這個查詢。Laravel 4.2一對一關係返回NULL

SELECT `path_filepath` from path where `path_id` = (SELECT `path_id` from file where file_id = 1) 

我想Filedb::find(1)->path()->path_filepath。但path()總是返回NULL。

[database] 

table: file 
file_id 
file_name 
path_id 

table: path 
path_id 
path_filepath 

型號

class Filedb extends Eloquent { 
     public $timestamps = false; 
     protected $table = 'file'; 
     protected $primaryKey = 'file_id'; 
     protected $connection = 'dl_database'; 

     public function path(){ 
      return $this->hasOne('Filepath','path_id','path_id'); 
     } 
} 


class Filepath extends Eloquent { 
     public $timestamps = false; 
     protected $table = 'path'; 
     protected $primaryKey = 'path_id'; 
     protected $connection = 'dl_database'; 

     public function filedb() 
     { 
      return $this->belongsTo('Filedb', 'path_id'); 
     } 
} 

我的控制器

var_dump(Filedb::find(1)->path()); 
echo '<br>'; 
$queries = DB::connection('dl_database')->getQueryLog(); 
$last_query = end($queries); 
var_dump($queries); 

Outout

NULL 
array(1) { [0]=> array(3) { ["query"]=> string(61) "select * from `file` where `file`.`file_id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(1) } ["time"]=> float(0.85) } } 

回答

0

belongsTo不hasOne

public function path(){ 
    return $this->belongsTo('Filepath','path_id','path_id'); 
} 

,這是hasOne

public function filedb() 
{ 
    return $this->hasOne('Filedb', 'path_id', 'path_id'); 
} 
+0

由於工作,但你路徑功能缺失的回報。 – dragon1993 2014-09-30 19:55:42

+0

@ dragon1993很好,是的,就像你的一樣。我從你的代碼複製粘貼它;) – 2014-09-30 21:53:21