如何在YII 2模型上手动更改主键

Riz*_*oro 5 php yii2

我尝试使用这种方式,但结果不是完整的列名.

class VMaterial extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'v_material';
    }


    /**
     * @inheritdoc$primaryKey
     */
    public static function primaryKey()
    {
        return "id";
    }
Run Code Online (Sandbox Code Playgroud)

结果:

SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'i'正在执行的SQL是:SELECT*FROM v_materialWHERE i='8'

pau*_*aul 6

有两种方法可以解决您的问题:

class VMaterial extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'v_material';
    }

    /**
     * @inheritdoc$primaryKey
     */
    public static function primaryKey()
    {
        return ["id"];
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

class VMaterial extends \yii\db\ActiveRecord
{
    public $primaryKey = "id";

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'v_material';
    }
}
Run Code Online (Sandbox Code Playgroud)