Fórum Duvida Insert tabela Muitos para Muitos #423950
18/09/2012
0
tenho 3 tabelas. Orders, Products e OrderDetails
CREATE TABLE `OrderDetails` ( `OrderID` int(11) NOT NULL, `ProductID` int(11) NOT NULL, `UnitPrice` double NOT NULL, `Quantity` int(11) NOT NULL, `Discount` int(11) DEFAULT NULL, KEY `fk_OrderDetails_1_idx` (`OrderID`), KEY `fk_OrderDetails_1_idx1` (`ProductID`), CONSTRAINT `fk_OrderDetails_Products` FOREIGN KEY (`ProductID`) REFERENCES `Products` (`ProductsID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_OrderDetails_Order` FOREIGN KEY (`OrderID`) REFERENCES `Orders` (`OrdersID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='latin1_swedish_ci'$$
CREATE TABLE `Orders` ( `OrdersID` int(11) NOT NULL AUTO_INCREMENT, `UnitPrice` int(11) NOT NULL, `Quantity` int(11) NOT NULL, `Discount` double DEFAULT NULL, PRIMARY KEY (`OrdersID`), ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='latin1_swedish_ci'$$
CREATE TABLE `Products` ( `ProductsID` int(11) NOT NULL AUTO_INCREMENT, `ProductName` varchar(35) NOT NULL, `SupplierID` int(11) NOT NULL, `CategoryID` int(11) NOT NULL, `QuantityPerUnity` int(11) NOT NULL, `UnitPrice` double NOT NULL, `UnitsInStock` int(11) NOT NULL, PRIMARY KEY (`ProductsID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='latin1_swedish_ci'$$
Agora vem as minhas duvidas ^^
1 - Na tabela OrderDetails eu coloquei o campo OrderID e o ProductID apenas como foreign key. É assim mesmo ? tem a necessidade de colocar os 2 campos como primary key tbm ?
2 - No meu codigo eu vou ter que fazer um insert para Product, Order e OrderDetails separadamente ? qual a melhor forma de fazer um insert ?
3 - É possivel eu adicionar o ID da tabela Product e o ID da tabela Order e preencher automaticamente a relação na tabela OrderDetails ?
Renato Chinaglia
Curtir tópico
+ 0Posts
25/09/2012
Felipe Medina
2 - A forma correta de inserir seria nessa ordem: Product, Order,OrderDetails. Como a tabela OrderDetails tem FK das anterirores será preciso que eles estejam preenchidas com as informações para a FK da OrderDetails.
3- Não é possível via banco, pode ser feito script ( trigger, procedure) que tenha uma regra que faça isso em alguma hipótese, que você define.
Gostei + 0
26/09/2012
Alisson Santos
Gostei + 0
26/09/2012
Renato Chinaglia
Respondida ^^
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)