Yii2 和 table 命名为 user_type 与用户 table 的用户模型的关系问题

Yii2 and table named user_type relation issue with User model of user table

我在 高级应用程序中有一个 user table 和一个 User 模型。 UserUserType 模型有一个关系,它的 table 被命名为 user_type 并且它与 Status 模型有一个关系,它的 table 被命名为statusStatusUserType这两个模型,与User模型有很多关系。

问题简而言之:在使用 DetailView 小部件的视图中,我发现了这个问题

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            ['attribute' => 'profileLink', 'format' => 'raw'],
            'id',            
            'email:email',
            'statusName', //This works Fine
            'userTypeName', // This DOES NOT Work
            'roleName',
            'created_at',
            'updated_at',
        ],
    ]) ?> 

使用userTypeName会出现以下错误:

Invalid Parameter – yii\base\InvalidParamException

Relation names are case sensitive. common\models\User has a relation named "userType" instead of "UserType".

我试过用UserTypeName替换它也给出同样的错误

只有在我使用惰性查询时才有效,即 'userType.user_type_name'!

但是,在 User 模型中,我已经在 attributeLabels() 方法中为 statusNameuserTypeName 定义了如下属性:

public function attributeLabels()
    {
        return [
        /* Your other attribute labels */
        'roleName' => Yii::t('app', 'Role'),
        'statusName' => Yii::t('app', 'Status'),
        /* ... */
        'userTypeName' => Yii::t('app', 'User Type'),
        'userTypeId' => Yii::t('app', 'User Type'),
        'userIdLink' => Yii::t('app', 'ID'),
        ];
    }

另外,我定义的关系如下:

public function getStatus()
    {
        return $this->hasOne(Status::className(), ['id' => 'status_id']);
    }

public function getUserType()
    {
        return $this->hasOne(UserType::className(), ['id' => 'user_type_id']);
    }

此外,我为 statusNameuserTypeName 定义了一个 getter,如下所示:

public function getStatusName()
    {
        return $this->status ? $this->status->status_name : '- no status -';
    }

public function getUserTypeName()
    {
        return $this->userType ? $this->UserType->user_type_name : '- no user type -';
    }

我无法找到导致 statusName 有效而 userTypeName 无效的问题根源。 table 或模型甚至方法是否有任何错误的命名约定?! table 名称是否以另一个相关 table 的名称开头导致此问题?即 useruser_type?

你应该更正 getUserTypeName,有一个错字:

public function getUserTypeName()
{
    return $this->userType ? $this->userType->user_type_name : '- no user type -';
}