Laravel 4.2一对一关系返回NULL

时间:2014-09-29 21:35:39

标签: sql laravel eloquent relationship

我想用Laravel一对一的关系来实现这个查询。

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

1 个答案:

答案 0 :(得分:0)

belongsTo没有一个

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

这是hasOne

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