Laravel ORM 关系 returns Laravel 5.2 为空

Laravel ORM relationship returns null on Laravel 5.2

我有两个模型 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');
    }

    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 记录。

companyuserType 关系之间的唯一区别是主键的数据类型。 company.company_id 是数字,而 user_type.user_type_id 是字符串。 我认为这与键的数据类型有关,但是,我在 Laravel 5.1 上有类似的设置并且运行完美。

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

public $incrementing = false;

在您的模型上 class。 我通过将 UserType 定义更改为:

来更正此问题
class UserType extends Model {
    protected $table = 'user_type';
    protected $primaryKey = 'user_type_id';
    public $incrementing = false;
}

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

但如果情况并非如此,用户属于 UserType,那么您必须将 hasOne 更改为 belongsTo。