使用 tableGateway 返回表主键名称

使用 tableGateway 返回表主键名称

问题描述:

我正在尝试为我的表对象创建一个抽象对象.

I'm trying to create an abstract object for my Table Objects.

今天我有很多对象,例如:CategoriaTableFornecedoresTable 等,它们实现了 $this->tableGateway->insert()$this->tableGateway->update()

Today I have lots of object like: CategoriaTable, FornecedoresTable, etc that implement $this->tableGateway->insert(), $this->tableGateway->update(), etc

我创建了一个包含大部分功能的 TableAbstract,但我遇到了一个问题:

I created an TableAbstract that contains most of those functionallities, but I stuck on one problem:

// 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?有更好的方法来做我想做的事吗?

How can I get from tableGateway the id of an table? There is an better way to do what I want?

我想我可以在我的对象中注入 id 名称,但我不认为这是一个很好的方法......

I guess I could inject the id name in my object but I don't thing this is a good way to do that...

您可以创建新的 TableGateway 类参数.(在我的例子中,我创建了 $this->primary;)

You can create new TableGateway class parameter.(In my case I created $this->primary;)

如果未设置,请使用 Zend\Db\Metadata\Metadata 直接从数据库结构中查找.

And if it is not set use Zend\Db\Metadata\Metadata to find it straight from db structure.

<?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;
    }
}
?>