有没有办法在Zend Framework中使用常规的mysql select语句,而无需使用Zend_Db :: factory
下面的代码在我的Model类中,它扩展了Zend_Db_Table_Abstract
我现在可以这样做(有效):
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'localhost',
'username' => 'dbuser',
'password' => 'dbuserpass',
'dbname' => "somedbname"
));
$select = "SELECT iv.*
FROM image_variations AS iv
LEFT JOIN images AS i ON (i.image_id = iv.image_id)
LEFT JOIN product_images AS pi ON (pi.image_id = iv.image_id)
WHERE pi.pid = '$pid'
&& iv.image_type_id = '$image_type_id' ";
$stmt = $db->query($select);
$rows = $stmt->fetchAll();
return $rows;
我想这样做:
$select = "SELECT iv.*
FROM image_variations AS iv
LEFT JOIN images AS i ON (i.image_id = iv.image_id)
LEFT JOIN product_images AS pi ON (pi.image_id = iv.image_id)
WHERE pi.pid = '$pid'
&& iv.image_type_id = '$image_type_id' ";
$stmt = $this->query($select);
$rows = $stmt->fetchAll();
return $rows;
所以我不必总是在每个方法中定义db变量并且在整个地方都有mysql密码。有没有办法使用$ this而不必实例化一个新的$ db Zend_DB Factory ??
答案 0 :(得分:0)
好的想通了。解决方案不是很优雅,但可以工作并且便携。
我的设置包含多个DB,因此在Bootstrap.php中我有:
protected function _initDatabase() {
$resource = $this->getPluginResource('multidb');
$resource->init();
Zend_Registry::set('db', $resource->getDb('db'));
Zend_Registry::set('shopdb', $resource->getDb('shopdb'));
}
在Application.ini中
resources.multidb.db.adapter = PDO_MYSQL
resources.multidb.db.host = 127.0.0.1
resources.multidb.db.username = user
resources.multidb.db.password = userpassword
resources.multidb.db.dbname = dbone
resources.multidb.db.isDefaultTableAdapter = true
resources.multidb.db.default = true
resources.multidb.shopdb.adapter = PDO_MYSQL
resources.multidb.shopdb.host = 127.0.0.1
resources.multidb.shopdb.username = user
resources.multidb.shopdb.password = userpassword
resources.multidb.shopdb.dbname = dbtwo
resources.multidb.shopdb.isDefaultTableAdapter = false
index.php中的
$config = new Zend_Config_Ini(APPLICATION_PATH . "/configs/application.ini");
Zend_Registry::set('settings', $config);
然后(模型中不是很优雅的位)添加一个init()方法
protected $db;
public function init() {
$settings = Zend_Registry::get('settings');
$adapter = $settings->production->resources->multidb->shopdb->adapter;
$params = array(
'host' => $settings->production->resources->multidb->shopdb->host,
'username' => $settings->production->resources->multidb->shopdb->username,
'password' => $settings->production->resources->multidb->shopdb->password,
'dbname' => $settings->production->resources->multidb->shopdb->dbname,
);
$this->db = Zend_Db::factory("$adapter", $params);
}
然后你可以在Model类的其他方法中使用$ this-> db,例如:
public function getProductImages($pid, $image_type_id) {
$select = "SELECT iv.*
FROM image_variations AS iv
LEFT JOIN images AS i ON (i.image_id = iv.image_id)
LEFT JOIN product_images AS pi ON (pi.image_id = iv.image_id)
WHERE pi.pid = '$pid'
&& iv.image_type_id = '$image_type_id' ";
$stmt = $this->db->query($select);
$rows = $stmt->fetchAll();
return $rows;
}
它有效,但似乎应该有更简单的方法...