2016-02-27 138 views
1

我有两个机型的用户和用户类型声明如下:Laravel ORM关系返回上Laravel空5.2

class User extends Model { 
    protected $table = 'user'; 
    protected $primaryKey = 'user_id'; 

    public function company() { 
     return $this->hasOne('App\Models\Company', 'company_id', 'company_id'); 
    } 

    public function userType() { 
     return $this->hasOne('App\Models\UserType', 'user_type_id', 'user_type_id'); 
    } 
} 

class UserType extends Model { 
    protected $table = 'user_type'; 
    protected $primaryKey = 'user_type_id'; 
} 

现在,我使用查询的关系:

User::with('userType', 'company')->all() 

奇怪的是,我得到公司但userType始终为空。 MySQL查询日志显示Laravel能够获取user_type记录。

公司USERTYPE之间的唯一区别关系是主键的数据类型。 company.company_id是数字,而user_type.user_type_id是一个字符串。 我认为它与键的数据类型有关,但是我在Laravel 5.1上有类似的设置,它运行的很好。

回答

0

Laravel支持非数字的主键,但你需要设置:

public $incrementing = false; 

在模型类上。 我改变用户类型定义来更正问题:

class UserType extends Model { 
    protected $table = 'user_type'; 
    protected $primaryKey = 'user_type_id'; 
    public $incrementing = false; 
} 
0

的第一个问题我与你的关系,注意的是,你传递给hasOne函数的第一个user_type_id是错误的,因为你有user_type_id作为主键user_type表。 hasone的第二个参数必须是用户父表的外键。因此,如果您在user_type表中有类似user_id的内容,请改用它。

但是,如果不是这种情况和用户而属于UserType那么你必须将hasOne更改为belongsTo。

+0

这个问题确实是我最初猜测的数据类型。看到我的答案。 – gmarintes