如何为连接的表返回现有行或默认行

时间:2013-07-01 18:52:37

标签: php codeigniter postgresql-9.1

我正在寻找一个更简单的查询来从连接表返回一行,就像它是新插入的默认值一样,除了理想情况下应该返回为NULL的主/外键。这样我就可以使用单个数据输入表单来添加新条目或编辑现有条目。

我正在使用CodeIgniter,DB_ActiveRecord类和postgre数据库驱动程序。

我想出的功能如下所示,我要简化的部分标有评论"如何优化?":

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;
}

0 个答案:

没有答案