douyu7879
2016-02-27 18:09
浏览 307
已采纳

Laravel ORM关系在Laravel 5.2上返回null

I have two models User and UserType declared as follows:

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';
}

Now, I query the relationships using:

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

Strangely, I get the company but userType is always null. The MySQL query log shows that Laravel was able to get the user_type record.

The only difference between company and userType relationships are the data type of the primary keys. company.company_id is numeric while user_type.user_type_id is a string. I think it is related to the data type of the keys however, I have a similar setup on Laravel 5.1 and it runs perfectly.

图片转代码服务由CSDN问答提供 功能建议

我有两个模型User和UserType声明如下:

  class User extends Model {
 protected $ table ='user'; 
 protected $ primaryKey ='user_id'; 
 
 public function company(){
 return $ this-> hasOne('App \ Models  \ Company','company_id','company_id'); 
} 
 
公共函数userType(){
返回$ 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始终为空。 .MQ查询日志显示Laravel能够获取user_type记录。 \ n

company userType 之间的唯一区别是pr的数据类型 imary键。 company.company_id 是数字,而 user_type.user_type_id 是一个字符串。 我认为它与键的数据类型有关但是,我在Laravel 5.1上有类似的设置 它完美运行。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtaidai0492 2016-02-27 18:09
    已采纳

    Laravel supports non-numeric primary keys but you need to set:

    public $incrementing = false;
    

    on your model class. I corrected the issue by changing UserType definition to:

    class UserType extends Model {
        protected $table = 'user_type';
        protected $primaryKey = 'user_type_id';
        public $incrementing = false;
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dragon7713 2016-02-27 19:53

    The first issue i notice with your relationship is that the first user_type_id you have passed to the hasOne function is wrong because you have the user_type_id as the primary key of the user_type table. The second argument of the hasone must be the foreign key of the parent table which is the user. So if you have anything like user_id in the user_type table use that instead.

    But if thats not the case and user rather belongs to UserType then you have to change the hasOne to belongsTo.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题