return table primary key name with tableGateway

夙愿已清 提交于 2019-12-24 03:35:23

问题


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

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

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()))

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

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


回答1:


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

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


来源:https://stackoverflow.com/questions/13646338/return-table-primary-key-name-with-tablegateway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!