模型关系在Yii2中未被识别

时间:2018-03-26 16:43:30

标签: model yii2 yii2-basic-app

我创建了2个名为User和ReferralsForm的模型,其中Users是父级,ReferralsForm是子级。我从用户分配给ReferralsForm有两个外键,但名称不同。我正在使用Gii生成我的模型以及关系。结构如下:

User
------------
users_id(PK),
display_name,
username,
email,
password,
member_since,
referral_hash

ReferralsForm
-------------
referral_id(PK),
userid(FK),
referred_user_id(FK),
status

用户模型关系代码和属性

public function getReferrals()
{
    return $this->hasMany(ReferralsForm::className(), ['userid' => 'user_id']);
}

public function getReferrals0()
{
    return $this->hasMany(ReferralsForm::className(), ['referred_user_id' => 'user_id']);
}

public function attributeLabels()
{
    return [
        'user_id' => 'Userid',
        'username' => 'Username',
        'email' => 'Email',
        'display_name' => 'Display Name',
        'password' => 'Password',
        'member_since' => 'Member Since',
        'auth_key' => 'Auth Key',
        'referral_hash' => 'Referral Hash',
    ];
}

ReferralsForm模型关系代码和属性标签

public function getUser()
{
    return $this->hasOne(User::className(), ['user_id' => 'userid']);
}

public function getReferredUser()
{
    return $this->hasOne(User::className(), ['user_id' => 'referred_user_id']);
}

public function attributeLabels()
{
    return [
        'id' => 'ID',
        'userid' => 'Userid',
        'referred_user_id' => 'Referred User ID',
        'subscription_id' => 'Subscription ID',
        'status' => 'Status',
    ];
}

这是我的控制器:

public function actionReferrals()
{
    $query = User::find()->joinWith('ReferralsForm');

    $model = new User();
    $ref_hash = $model->getHash();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);  
    return $this->render('referrals' ,['dataProvider' => $dataProvider, 'ref_hash' => $ref_hash]);
}

仍然给我一个错误

Invalid Argument – yii\base\InvalidArgumentException
app\models\User has no relation named "ReferralsForm".

Caused by: Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\models\User::getReferralsForm()

1 个答案:

答案 0 :(得分:1)

如果你有一个关系名称推荐(getReferrals()),你应该在你的joinWith中使用推荐

$query = User::find()->joinWith('referrals');