我正在创建社交网站和И墙,在那里可以获取用户帖子。当用户创建新帖子时,他们可以选择附加照片。Post和附件具有不同的数据库表以及不同的控制器和模型。
问题是,当我执行插入新post的查询时,И需要再查询一个将保持post_id的附件。所以首先我需要在数据库中插入帖子,然后И需要为该帖子插入附件?但是,当所有查询都在一段时间内执行时,如何获取该帖子的id?
让我们看看我的表格:
张贴
post_id account_id post_text
------- ---------- -----------------------
1 1 Hello world post
附件
attachment_id post_id attachment_type attachment_name
------------- ------- --------------- -----------------
1 1 3 photo_1.jpg
2 1 2 video_1.mp4
3 1 3 photo_2.jpg
我不想为此使用交易。
提交时,我需要插入:
INSERT INTO post bla bla bla
INSERT INTO attachments bla bla bla <post_id> //how to get it when is executed in some time?
如果您使用的是codeigniter,那么必须有一些选项来获取之前以这种方式使用的插入id。。。。。。
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
您必须从post
表中获取最后插入的id,然后将insert
获取到具有引用id 的attachments
表中
INSERT INTO post (<FIELDS>) VALUES (<VALUES)
$pdo->insert('posts', $yourData);
$lastInsertId = $pdo->lastInsertId();
然后你必须插入attachments
INSERT INTO attachments (<FIELDS>) VALUES (<VALUES)