简体   繁体   中英

Can anyone help me how to insert the same id in different tables

How to insert the same id in different tables at a time in one table. it is a primary key and autoincrement and in another table. It is a foreign key at a time. I have to insert in both the tables using OpenCrat.

$this->db->query("INSERT INTO " 
. DB_PREFIX .   "xyz
SET 
    boutiques_id = '" . (int)$this->customer->getId() . "',
    boutique_customer_id = '" . $this->db->escape($data['boutique_customer_id']) . "',
    ordered_date = '" . $this->db->escape($data['ordered_date']) . "',
  '");

$this->db->query("INSERT INTO " 
. DB_PREFIX .   "abc 
SET 
    boutiques_id = '" . (int)$this->customer->getId() . "',
    firstname = '" . $this->db->escape($data['firstname']) . "', 
    lastname        = '" .$this->db->escape($data['lastname']). "',

    }

in abc table it is a primary key and autoincrement whereas in second table it is foreign key.

After an insert query use this $this->db->getLastId(); to get last inserted id of that table, by this u can add this to another table.

The ghetto way assuming there is a unique constraint on boutique_customer_id and ordered_date would be:

INSERT INTO abc (boutiques_id, firstname, lastname)
SELECT boutiques_id, 'John', 'Smith'
FROM xyz
WHERE boutique_customer_id = 123
AND ordered_date = 2015-05-01

Or else you would need to use a transaction/programmatically get and set that foreign key value. Either way I wouldn't try to set the primary key when initially inserting. Finally unrelated to your question, try looking at using an ORM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM