zend-framework2 - 使用 tableGateway 返回表主键名称

标签 zend-framework2

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

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

我创建了一个包含大部分功能的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?有更好的方法来做我想做的事吗?

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

最佳答案

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

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

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

关于zend-framework2 - 使用 tableGateway 返回表主键名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646338/

相关文章:

zend-framework2 - 0x7002 : LDAP extension not loaded in ZF2

debugging - ZF2 - 如何启用Twig的调试/转储功能

php - ZF2 - 将数组绑定(bind)到单个数据库查询参数

php - 如何将带下划线的表列映射到 ZF2 中的驼峰式模型类属性?

zend-framework - 如何在 ZF2 中禁用布局和 View 渲染器?

PHP 框架和项目存储库

mysql - Zend 2 与数据库的单独访问控制

php - 使用 Doctrine 和 ZF2 进行分页

php - Zend Framework 2 - 用于教义和注释表单的 Magic Getter 和 Setter

events - 如何触发附加到 ZF2 中共享事件管理器的事件?