2011-07-23 44 views
1

我在Zend框架中得到的模型什么延伸Zend_Db_Table其中$this->_name = 'tableA'从另一个表zend框架更新

这是非常好的,我在做多长时间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 = ..... 

如何建立PARAMS为update()方法:

parent::update($data, $where); 

回答

1

有没有可能的组合如何构建parent::update()方法的参数以获得最终更新查询。原因是因为Db表update方法只是将您的$data$where变量传递给Db适配器的方法update。适配器的update方法没有留下附加信息的余地。 你不能破解参数

如果你不能使用表关系与级联更新。最好的办法是扩展Db适配器并创建一个新的方法来处理这些类型的更新。这应该工作。

/** 
* 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); 
} 

注:我没有测试了这一点,但我非常有信心预期它会工作。如果您有任何问题,请告诉我。因为我复制了适配器的更新方法,所以我继续添加注释,说明为什么不能破解这些参数。

编辑 我差点忘了提。每个适配器都是独一无二的,因此您必须检查适配器更新方法。我刚刚从Zend_Db_Abstract复制。