2012-11-30 59 views
2

我想为我的表对象创建一个抽象对象。返回表主键名与表网关

今天我有很多目标,如:CategoriaTableFornecedoresTable等实现$this->tableGateway->insert()$this->tableGateway->update()

我创建了一个包含大多数的functionallities的TableAbstract,但我被困在一个问题:

// In CategoriaTable my table id is named cat_id 
$this->tableGateway->update($object->getArrayCopy(),array('cat_id' => $object->getId())) 

// But in FornecedoresTable my table id is named for_id 
$this->tableGateway->update($object->getArrayCopy(),array('for_id' => $object->getId())) 

如何从tableGateway获得表的id?有更好的方法去做我想做的事情?

我想我可以在我的对象注入ID名字,但我不知道的事情,这是做一个好办法...

+0

我建议另一种方式(通过使用MetadataFeature)这里 http://stackoverflow.com/questions/23428786/zf2-tablegateway-how-to-get-primary-key/31725804# 31725804 – xsubira

回答

3

您可以创建新TableGateway类参数。(在我的情况,我创建$ this-> primary;)

如果没有设置,使用Zend \ Db \ Metadata \ Metadata直接从db结构中找到它。

<?php 
//... 
use Zend\Db\TableGateway\AbstractTableGateway; 
use Zend\Db\Metadata\Metadata; 

class AbstractTable extends AbstractTableGateway 
{ 
    protected $primary; 

    public function getPrimary() 
    { 
     if (null === $this->primary) { 
      $metadata = new Metadata($this->adapter); 
      $constraints = $metadata->getTable($this->getTable()->getTable()) 
            ->getConstraints(); 

      foreach ($constraints AS $constraint) { 
       if ($constraint->isPrimaryKey()) { 
        $primaryColumns = $constraint->getColumns(); 
        $this->primary = $primaryColumns; 
       } 
      } 
     } 

     return $this->primary; 
    } 
} 
?> 
+1

不错的答案。但是这个方法调用'$ metadata-> getTable($ this-> getTable() - > getTable()) - > getConstraints()'应该超级慢吗? – MurifoX