Php Codeigniter Postgresql:具有外键死锁的事务
我对postgresql事务(使用codeigniter)有问题,下面是相关的表:Php Codeigniter Postgresql:具有外键死锁的事务,php,sql,codeigniter,postgresql,Php,Sql,Codeigniter,Postgresql,我对postgresql事务(使用codeigniter)有问题,下面是相关的表: CREATE TABLE factura( nro_factura serial NOT NULL, fecha_emision date NOT NULL, (... more columns) PRIMARY KEY (nro_factura)); CREATE TABLE detalle( id_articulo integer NOT NULL REFERENCES articulos(id)
CREATE TABLE factura(
nro_factura serial NOT NULL,
fecha_emision date NOT NULL,
(... more columns)
PRIMARY KEY (nro_factura));
CREATE TABLE detalle(
id_articulo integer NOT NULL REFERENCES articulos(id) ON UPDATE CASCADE ON DELETE RESTRICT,
nro_factura integer NOT NULL REFERENCES factura(nro_factura) ON UPDATE CASCADE ON DELETE RESTRICT,
(... more columns)
PRIMARY KEY(id_articulo,nro_factura));
这就是交易:
$this->db->trans_start();
$queryFactura = $this->db->query("INSERT INTO factura (... all columns) VALUES (CURRENT_DATE,?,?,?,?,?,?,?,?,?,?,?,?)",$factura);
$id_factura = $this->db->query("SELECT nro_factura FROM factura WHERE id_vehiculo=?",array($factura['id_vehiculo']));
foreach ($articulos as $key){
$queryFactura = $this->db->query("INSERT INTO detalle (id_articulo,nro_factura,precio_venta,descuento,cantidad) VALUES (?,$id_factura,?,?,?)",$key);
}
$this->db->trans_complete();
现在,我无法执行SELECT查询,因为尚未进行上一次插入。如何在没有第一次插入的外键的情况下进行第二次插入
编辑:24/06/2014
最后,我使用了postgre的currval()函数。仅替换此项的select查询:
$id_factura = $this->db->query("SELECT currval(pg_get_serial_sequence('factura', 'nro_factura'))",array())->result()[0]->currval;
如果您只需要INSERT语句中的“nro_factura”值,那么不应该使用SELECT语句来获取它 PostgreSQL公开了特定序列通过its返回的最后一个数字。它的记录行为是 返回nextval最近为此序列获取的值 在本届会议上。(如果nextval从未执行过,则会报告错误。) 已在此会话中为此序列调用。),因为这是 返回一个会话本地值,它给出了一个可预测的答案 或者自当前会话以来没有其他会话执行nextval 是的 CodeIgniter似乎围绕PostgreSQL函数包装了自己的函数
好的,目前广泛使用的每个dbms、每个ORM和每个数据库抽象层的版本都包含这样一个函数。谢谢,最后我使用了currval函数,它可以工作了。