编程语言
首页 > 编程语言> > PHP-Phalcon获取枚举值

PHP-Phalcon获取枚举值

作者:互联网

我正在使用很多具有“枚举”和“设置”类型的列的数据库.我的观点是要在Phalcon控制器中获取列的值.我发现了一些代码片段,但是在Phalcon中却没有任何内容,当我尝试执行它们时,似乎Phalcon出现了一些问题.

public function getEnumValues(){
    $sql  = "SHOW COLUMNS FROM profiles LIKE 'eyes_color'";

    $query = new \Phalcon\Mvc\Model\Query($sql, $this->getDI());
    $result = $query->execute();

    return $result;
}

返回值:

Syntax error, unexpected token IDENTIFIER(SHOW), near to ‘ COLUMNS FROM profiles LIKE ‘eyes_color”, when parsing: SHOW COLUMNS FROM profiles LIKE ‘eyes_color’

方法二:

public function getEnumValues(){
    $sql = "SELECT COLUMN_TYPE FROM COLUMNS WHERE TABLE_NAME = 'profiles' AND COLUMN_NAME = 'hair_color'";

    $query = new \Phalcon\Mvc\Model\Query($sql, $this->getDI());
    $result = $query->execute();

    return $result;
}

返回值:

Model ‘COLUMNS’ could not be loaded

我将不胜感激.

解决方法:

这是您需要的工作版本:

$config = $this->getDI()->get('config');
$pdo    = new \Phalcon\Db\Adapter\Pdo\Mysql([
    "host"     => $config->database->host,
    "username" => $config->database->username,
    "password" => $config->database->password,
    "dbname"   => $config->database->dbname,
]);
$sql = "
    SELECT TRIM(TRAILING ')' FROM SUBSTRING(COLUMN_TYPE,6)) AS enum_list
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA='my_db_name'
        AND TABLE_NAME='my_table_name'
        AND COLUMN_NAME='my_column_name'
";
$result    = $pdo->query($sql)->fetch();
$enumArray = array();
if (!empty($result['enum_list'])) {
    $enumArray = explode(',', $result['enum_list']);
    foreach ($enumArray as &$value) {
        $value = trim($value, "'");
    }
}
echo "<pre>"; var_dump($enumArray); die;

标签:phalcon,mysql,php
来源: https://codeday.me/bug/20191120/2044544.html