如何在Yii 2 crud生成器模板中获取主键

时间:2016-03-29 16:16:57

标签: yii2

我使用gii代码生成器,我想在

中获取主键
C:\wamp\www\yii2\vendor\yiisoft\yii2-gii\generators\model/default/views/index.php

Yii使用此代码

$count = 0;
if (($tableSchema = $generator->getTableSchema()) === false) {
    foreach ($generator->getColumnNames() as $name) {
        if (++$count < 6) {
            echo "            '" . $name . "',\n";
        } else {
            echo "            // '" . $name . "',\n";
        }
    }
} else {
    foreach ($tableSchema->columns as $column) {
        $format = $generator->generateColumnFormat($column);
        if (++$count < 6) {
            echo "            '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
        } else {
            echo "            // '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
        }
    }
}

我想在获得代码之前获得primaryKey。

  

$发电机 - &GT; getTableSchema() - &GT;的PrimaryKey();

但无效。

3 个答案:

答案 0 :(得分:2)

该功能无法返回您想要的内容。它将返回可能是主键的name属性,也可能不是。如果添加一个名为&#34; name&#34;的列在您的数据库中,将返回该列的名称而不是主键。

此外,该函数的目的是返回1列的名称。那1列可能不是完整的主键,它可能是它的一部分,如果你的主键再次由多列组成,那么这个功能将使你失败。

获得它的正确方法是

$class = $this->modelClass;
$pk = $class::primaryKey();

和$ pk是一个数组。

你的答案可以解决你的问题(我在我的代码中也使用了类似的东西),但它并没有真正回答你的问题(如何获得主键)。

答案 1 :(得分:0)

我从

找到了一个函数
  

C:\瓦帕\ WWW \ yii2 \厂商\ yiisoft \ yii2-GII \发电机\污物\ Generator.php

函数是getNameAttribute()

 public function getNameAttribute()
{
    foreach ($this->getColumnNames() as $name) {
        if (!strcasecmp($name, 'name') || !strcasecmp($name, 'title')) {
            return $name;
        }
    }
    /* @var $class \yii\db\ActiveRecord */
    $class = $this->modelClass;
    $pk = $class::primaryKey();

    return $pk[0];
}

我在文件中成功地调用了以下代码:

  

C:\瓦帕\ WWW \ yii2 \厂商\ yiisoft \ yii2-GII \发电机\模型/默认/视图/ index.php的

,例如

<?= $generator->getNameAttribute(); ?>//id

或者很快

<?= $nameAttribute; ?>

答案 2 :(得分:0)

$generator->getTableSchema()->primaryKey();

不是方法,属性是:

$generator->getTableSchema()->primaryKey;

这会返回一个数组,为了获取列名,你必须访问数组的第一个元素,比如

$generator->getTableSchema()->primaryKey[0];

另一方面,你可以:

  foreach ($generator->getTableSchema()->columns as $column) {
    if ($column->isPrimaryKey) {
      // your code
    }