How do I insert into a ternary relationship?

0

I am creating this template yet I do not know if it is correct. Because I have basic knowledge in database.

How do I insert into a ternary relationship that happens in Supplier - Suppliers_has_product - Product?

    
asked by anonymous 22.03.2014 / 14:42

1 answer

1

Your relationship seems to me correct, yes. You register suppliers, products, and when you want to associate a vendor with a product (in a many-to-many relationship) you use your IDs in the intersection table ( fornecedor_has_produto ).

If you do not know the IDs, you just have just entered a vendor and / or product and want to get the ID auto-assigned by the bank, use the LAST_INSERT_ID . Usually, the library you are using to connect to the bank (eg PDO , mysqli ) will have a function to do this for you (since it is a common feature) .

A (simplified) example using PDO :

/* Conecta ao banco de dados */
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);

/* Insere um fornecedor */
$stmt = $dbh->prepare("insert into fornecedor(nome, cnpj, ...) values(:nome, :cnpj, ...);");
$stmt.bindParam(":nome", $nome_do_fornecedor);
$stmt.bindParam(":cnpj", $cnpj_do_fornecedor);
...
$stmt->execute();

/* Obtém o ID do fornecedor inserido */
$id_fornecedor = $dbh->lastInsertId()

/* Insere um produto */
...

/* Obtém o ID do produto inserido */
$id_produto = $dbh->lastInsertId()

/* Relaciona o fornecedor com o produto */
$stmt = $dbh->prepare("insert into fornecedor_has_produto(fornecedor_id, produto_id) values(:fornecedor, :produto);");
$stmt.bindParam(":fornecedor", $id_fornecedor, PDO::PARAM_INT);
$stmt.bindParam(":produto", $id_produto, PDO::PARAM_INT);
$stmt->execute();

(I have no practical experience with PHP, I've set up this example from other online examples, but it should have been able to demonstrate what needs to be done.) If you want an example with mysqli instead, I can do it.)

    
22.03.2014 / 15:28