我很难在我的某个模型中设置虚拟字段。我在所有模型中都设置了这样的虚拟场,没有任何问题。但是,出于某些原因我无法弄清楚,在这个模型中它根本不起作用。
错误:
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`
答案 0 :(得分:0)
以下是我最终用于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' => ''
)
);
}