增加FK值而不是使用选定的FK值

时间:2013-11-22 12:40:08

标签: php postgresql yii

我使用postgresql db。使用Yii框架构建了一个PHP Web应用程序。

以下是我的表apresentanteveiculoferrolavagem

CREATE TABLE apresentante
(
  id serial NOT NULL,
  nome character varying(50) NOT NULL,
  morada character varying(50),
  cp character varying(15),
  nif integer NOT NULL,
  telefone integer,
  telemovel integer,
  codigo integer NOT NULL,
  CONSTRAINT apresentante_pkey PRIMARY KEY (id)
)
WITHOUT OIDS;

CREATE TABLE veiculo
(
  id serial NOT NULL,
  matricula character varying(20) NOT NULL,
  classe character varying(10) NOT NULL,
  CONSTRAINT id_veiculo PRIMARY KEY (id)
)
WITHOUT OIDS;

CREATE TABLE lavagem
(
  id serial NOT NULL,
  veiculo_id serial NOT NULL,
  data date NOT NULL,
  apresentante_id smallint NOT NULL,
  ferro_id serial NOT NULL,
  apresentante_paga boolean NOT NULL,
  CONSTRAINT id_lavagem_pkey PRIMARY KEY (id),
  CONSTRAINT id_apresentante_fk FOREIGN KEY (apresentante_id)
      REFERENCES apresentante (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT id_ferro_fk FOREIGN KEY (ferro_id)
      REFERENCES ferro (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT id_veiculo_fk FOREIGN KEY (veiculo_id)
      REFERENCES veiculo (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITHOUT OIDS;

CREATE TABLE ferro
(
  id serial NOT NULL,
  ferro integer NOT NULL,
  nome character varying(50) NOT NULL,
  CONSTRAINT id_ferro PRIMARY KEY (id)
)
WITHOUT OIDS;

我用Gii创建了模型和表单。 问题是当我尝试在表lavagem中插入一行时,它没有获得所选的FK值,而是将FK值增加到FK表中不存在的值。

异常错误:

CDbException

CDbCommand failed to execute the SQL statement: SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "lavagem" violates foreign key constraint "id_ferro_fk"
DETAIL: Key (ferro_id)=(4) is not present in table "ferro".. The SQL statement executed was: INSERT INTO "lavagem" ("data", "apresentante_id", "apresentante_paga") VALUES (:yp0, :yp1, :yp2)

谢谢

1 个答案:

答案 0 :(得分:1)

您的架构中有错误。外键如:

veiculo_id serial NOT NULL,

实际上看起来应该更像:

veiculo_id int NOT NULL,

原始表中的id字段需要是一个自动递增的整数;而不是引用它的字段。