我在Zend框架中得到了扩展Zend_Db_Table
的模型,其中$this->_name = 'tableA'
。
我做insert()
, update()
或delete()
的时间很长。如何实现基于另一个表的值更新主表…
在原始SQL查询中,它看起来像这样:
UPDATE tableA SET fieldA = tableB.newValue
FROM tableB
WHERE tableA.someValue = tableB.someIndex // it will be complicate manipulation
AND tableA.index = .....
如何为update()
方法构建参数:
parent::update( $data, $where );
对于如何为parent::update()
方法构建参数以获得最终更新查询,没有可能的组合。原因是Db Table update
方法只是将$data
和$where
变量传递给Db Adapter的update
方法。适配器的update
方法没有留下附加附加信息的空间。你根本不能破解参数
如果你不能使用表关系级联更新。您最好的选择是扩展Db Adapter并创建一个新方法来处理这些类型的更新。这应该可以工作。
/**
* Add this method to you custom adapter
* Direct copy of update method with integration of $from
* @see Zend_Db_Adapter_Abstract::update
**/
public function updateFrom($table, $from, array $bind, $where = '')
{
/**
* Build "col = ?" pairs for the statement,
* except for Zend_Db_Expr which is treated literally.
*/
$set = array();
$i = 0;
foreach ($bind as $col => $val) {
if ($val instanceof Zend_Db_Expr) {
$val = $val->__toString();
unset($bind[$col]);
} else {
if ($this->supportsParameters('positional')) {
$val = '?';
} else {
if ($this->supportsParameters('named')) {
unset($bind[$col]);
$bind[':col'.$i] = $val;
$val = ':col'.$i;
$i++;
} else {
/** @see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
}
}
}
// Reason #1 you can't hack into $data array to pass reference to a table
$set[] = $this->quoteIdentifier($col, true) . ' = ' . $val;
}
$where = $this->_whereExpr($where);
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->quoteIdentifier($table, true)
. ' SET ' . implode(', ', $set)
. ' FROM ' . $this->quoteIdentifier($from, true) // My only edit
. (($where) ? " WHERE $where" : ''); // Reason #2 no room in where clause
/**
* Execute the statement and return the number of affected rows
*/
if ($this->supportsParameters('positional')) {
$stmt = $this->query($sql, array_values($bind));
} else {
$stmt = $this->query($sql, $bind);
}
$result = $stmt->rowCount();
return $result;
}
/** Add this to your extended Zend_Db_Table **/
public function update(array $data, $where)
{
$tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
$from = 'schema.name'; // Get from table name
return $this->_db->updateFrom($tableSpec, $from, $data, $where);
}
注意:我没有测试过这个,但我很有信心它会像预期的那样工作。如果你有任何问题,请告诉我。因为我复制了适配器的update方法,所以我继续并添加了不能破解这些参数的原因注释。
编辑我差点忘了说。每个适配器都是唯一的,因此您必须检查适配器更新方法。我只是从Zend_Db_Abstract
复制。
我想你需要这个:http://framework.zend.com/manual/en/zend.db.table.relationships.html