Yii2 - Gii 模型关系 - 为什么函数名称后有 0?

Yii2 - Gii Model Relations - Why is there a 0 after the function names?

在查看其他人的代码、指南、教程等时,我还没有在网上看到这个

当我用 Gii 生成模型时,关于关系的函数后面都有一个零。


示例:

class Benefit extends \yii\db\ActiveRecord
{
    // truncated Yii Model code...

    public function getType0()
    {
        return $this->hasOne(BenefitTypes::className(), ['id' => 'type']);
    }
}

BenefitTypes 是一个 ID 到名称的映射:

id | name
---------------
1  =>  Federal
2  =>  Non-Profit

在 'benefit' table 中,它有一个名为 'type' 的列,它与 'benefit_types' table 'id' 列有关系。

虽然我应该可以做到(在 /views/benefit/index.php)'type.name' 但它也不起作用。它将列名称更改为 "Type Name" 并将“(未设置)”放入数据 table...

示例:

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'id',
        'somevalue',
        'type.name',
    ],
]) ?>

这是怎么回事,为什么它不像预期的那样运行?


更新

我开始认为关系函数名称的 0 后缀,即:getType0,是由于 "type" 在 table 中用作列名以避免重复或混淆。虽然我找不到这个记录,所以想对此有一个明确的答案。

我将函数名称更改为 getTypeRelation()。然后在 index.php 视图中,对于 detailview 小部件,使用 'typeRelation.name' 并通过关系返回名称就好了。

你的想法是正确的。关系名称的生成由函数 generateRelationName().

完成
protected function generateRelationName($relations, $table, $key, $multiple)
{
    if (!empty($key) && substr_compare($key, 'id', -2, 2, true) === 0 && strcasecmp($key, 'id')) {
        $key = rtrim(substr($key, 0, -2), '_');
    }
    if ($multiple) {
        $key = Inflector::pluralize($key);
    }
    $name = $rawName = Inflector::id2camel($key, '_');
    $i = 0;
    while (isset($table->columns[lcfirst($name)])) {
        $name = $rawName . ($i++);
    }
    while (isset($relations[$table->fullName][$name])) {
        $name = $rawName . ($i++);
    }
    return $name;
}

Yii 使用相关 table 的名称作为关系名称。如果你有一个与相关 table 同名的列,一个数字将附加到关系以避免由于 Yii 处理魔法函数而造成的混淆。如果在与相同 table 相关的单个 table 中有两列或更多列,也会发生这种情况,例如列 create_user_idupdate_user_iddelete_user_id 与 table user 将导致名为 useruser0user1.

的关系

对于您的示例,建议您将外键字段命名为其他名称,例如 type_idtypeId。 Yii 会正确处理这些。当您有多个列与同一个 table 相关时,另一种选择是重命名函数。

因为关系列名和关系名相同。当您调用 $benefit->type 时,您会期望什么,column/property type 的值或 BenefitTypes 的实例?所以现在你知道了。 $benefit->type return 属性 值和 $benefit->type0 return 关系实例。