0

当 zf2 工作时,它就像魔法一样,当它不工作时,它是令人抓狂的。我确定我遗漏了一些小东西或做错了,但是什么?我要做的就是获取 postgresql 表中最后插入的行的 id。

这是我的代码:

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;

class LogTable extends AbstractTableGateway
{
    protected $table = 'log';

    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Log());

        $this->initialize();
    }

    public function saveLog(Log $log)
    {
        $data = array(
            'guid'      => $log->guid,
            'user_id'   => $log->user_id,
            'client_id' => $log->client_id,
            'log_time'  => $log->log_time,
            'severity'  => $log->severity,
            'source'    => $log->source,
            'line'      => $log->line,
            'module'    => $log->module,
            'function'  => $log->function,
            'category'  => $log->category,
            'action'    => $log->action,
            'message'   => $log->message,
        );

        $id = (int)$log->id;
        if ($id == 0) {
            $this->insert($data);
            $id = $this->lastSequenceId('log_id_seq');
            print("id is $id");
        } else {
            if ($this->getLog($id)) {
                $this->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
        return $id;
    }
}

插入以预期的规律发生,但由于某种原因 ZF2 讨厌这条线

$id = $this->lastSequenceId('log_id_seq');

我在其他地方看到过这个:

$newID = $db->lastSequenceId('comments_comment_id_seq');

我假设他们的 $db 对应于我的 $this,因为他们也有 $db->insert 而我有 $this->insert。

我什至尝试将它添加到我的构造函数中:

use Zend\Db\TableGateway\Feature;
...
$this->featureSet = new Feature\FeatureSet();
$this->featureSet->addFeature(new Feature\SequenceFeature('id','log_id_seq'));

但这只会给出这样的错误:

SQLSTATE[42601]: Syntax error: 7 ERROR:  syntax error at or near ")"

第 1 行:插入“日志”() 值 ()

所以也许这来自另一个 ZF2 版本,不适用于 2.1.5。

知道这里发生了什么吗?有什么方法可以强制 zf2 给我最新的 id 吗?

4

1 回答 1

0

没有一种简单的方法可以在 PostgreSQL 中执行与此 API 完全等效的操作,您希望改为使用 SQL 并运行:

SELECT currval('[sequence0name]');

例如:

SELECT currval('mytable_mycol_id_seq');

Currval 是多会话安全的,并且该值与当前数据库会话相关联。

于 2013-10-26T06:41:10.227 回答