我正在寻找一个更简单的查询来从连接表中返回一行,就好像它是用默认值新插入的一样,除了理想情况下应该返回为 NULL 的主键/外键。这样我就可以使用单个数据输入表单来添加新条目或编辑现有条目。
我正在使用 CodeIgniter、DB_ActiveRecord 类和 postgre DB 驱动程序。
我想出的功能如下所示,我想简化的部分标有注释“如何优化?”:
public function get_entry()
{
$id = $this->input->post('id');
if ($id) {
// Get existing entry from joined tables.
$query = $this->db
->join('b', 'a.id = b.id')
->get_where('a', array('a.id' => $id));
} else {
// Get a new "default" entry from joined tables.
// How to optimize? Ideally it would:
// 1. Not need a transaction.
// 2. Not insert (causes holes in the id sequence.)
// 3. Not use a PHP trick of overlaying same-named results.
$this->db->trans_begin();
// Note: I modified insert() so that empty array gives "DEFAULT VALUES"
// and 3rd parameter gives "RETURNING ..."
$query = $this->db
->insert('a', array(), 'id');
if ($this->db->trans_status() and $query->num_rows()) {
$id = $query->row()->id;
$query = $this->db
->insert('b', array('id' => $id));
if ($this->db->trans_status() and $query) {
$query = $this->db
// Note: This trick overlays NULL onto value in id
->select('*, NULL AS id')
->join('b', 'a.id = b.id')
->get_where('a', array('a.id' => $id));
}
}
// Note: Trash the temporary insert.
$this->db->trans_rollback();
}
if ($query and $query->num_rows()) {
return $query->result();
}
return FALSE;
}