我的表格如下:
CREATE TABLE data.brand_list
(
id bigserial NOT NULL,
brand_name text,
created_at timestamp with time zone DEFAULT now(),
ghost boolean,
CONSTRAINT brand_list_id_pkey PRIMARY KEY (id)
)
它也有序列:
CREATE SEQUENCE data.brand_list_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 649
CACHE 1;
ALTER TABLE data.brand_list_id_seq
我在Zend模型中的代码:
public function addRow(BrandList $brandList)
{
$data = array(
'id' => $brandList->id,
'brand_name' => $brandList->brand_name,
'created_at' => $brandList->created_at,
'ghost' => $brandList->ghost,
);
$id = (int)$brandList->id;
if ($id == 0) {
unset($data['id']);
$row = $this->tableGateway->insert($data);
var_dump($this->tableGateway->getLastInsertValue());die;
return $id;
} else {
if ($this->findOne($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
并且$ row总是返回int(1),$ this-> tableGateway-> getLastInsertValue()返回NULL。我究竟做错了什么?我已经尝试了一切......没有运气。
答案 0 :(得分:1)
您可以尝试原始查询,看看您是否获得了所需的结果。
$adapter = $this->tableGateway->getAdapter();
$rowset = "SELECT MAX(ID)...";
$resultset = $adapter->query($rowset,array());
$rowData = $resultset->toArray();
return $rowData;
OR
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
Use Zend\Db\Sql\Expression;
$adapter = $this->tableGateway->getAdapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('table_name')->columns(array('id' => new Expression('max(id)') ));
$selectString = $sql->getSqlStringForSqlObject($select);
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
$resultSet = new ResultSet();
$resultSet->initialize($results);
return $resultSet->toArray();
答案 1 :(得分:0)
嗯,我发现也许不是太优雅的解决方案,但它对我有用。我发现了什么 - Zend 2有postgres序列的问题。这是我的解决方案:
$sql = "SELECT nextval('data.brand_list_id_seq') nextval";
$resultSet = $this->tableGateway->getAdapter()->getDriver()->getConnection()->execute($sql);
foreach ($resultSet as $item) {
$data['id'] = $item['nextval'];
}
$this->tableGateway->insert($data);
return $data['id'];
您应该将以上代码应用于模型插入方法。
答案 2 :(得分:0)
尝试$this->tableGateway->lastInsertValue;
而不是$this->tableGateway->lastInsertValue();