在模型中创建虚拟字段时出错


Error when creating a virtual field inside a model

我很难在我的一个模型中设置一个虚拟字段。我一直在我所有的模型中设置这样的虚拟字段,没有任何问题。然而,由于某种原因我不知道,它在这个模型中根本不起作用。

错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'databases WHERE id = `DataSourceName`.`database_id`) AS `DataSourceName__databa' at line 1

模型:

<?php
App::uses('AppModel', 'Model');
/**
 * DataSourceName Model
 *
 * @property Database $Database
 */
class DataSourceName extends AppModel {
    public $virtualFields = array(
            'database' => 'SELECT name FROM databases WHERE id = DataSourceName.database_id',
    );
    //The Associations below have been created with all possible keys, those that are not needed can be removed
/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'Database' => array(
            'className' => 'Database',
            'foreignKey' => 'database_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
}
SQL:

CREATE TABLE IF NOT EXISTS data_source_names(
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) DEFAULT NULL,
  description VARCHAR(255) DEFAULT NULL,
  database_id INT(10) UNSIGNED DEFAULT NULL,
  created DATETIME DEFAULT NULL,
  modified DATETIME DEFAULT NULL,
  created_by INT(10) UNSIGNED DEFAULT NULL,
  modified_by INT(10) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (id)
)
ENGINE = INNODB
AUTO_INCREMENT = 1
CHARACTER SET utf8
COLLATE utf8_unicode_ci;

更新1

SQL失误:

(SELECT name FROM databases WHERE id = `DataSourceName`.`database_id`) AS `DataSourceName__database`

下面是我最终使用的SQL:

SELECT name FROM my_db.databases WHERE id = `DataSourceName`.`database_id`

请注意数据库名称前缀(例如。my_db)在表databases前面。可能是因为databases是一个保留字。

最终模型:

<?php
App::uses('AppModel', 'Model');
/**
 * DataSourceName Model
 *
 * @property Database $Database
 */
class DataSourceName extends AppModel {
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        $fields = get_class_vars('DATABASE_CONFIG');
        $this->virtualFields['database'] = sprintf(
                'SELECT name FROM %s.databases WHERE id = DataSourceName.database_id', $fields['default']['database']
        );

    }
    //The Associations below have been created with all possible keys, those that are not needed can be removed
/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'Database' => array(
            'className' => 'Database',
            'foreignKey' => 'database_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
}