【问题标题】:CodeIgniter transactions with multiple functions具有多种功能的 CodeIgniter 事务
【发布时间】:2017-11-24 09:26:08
【问题描述】:

我需要在“产品”表中添加一个产品,我得到添加的产品ID,然后在“产品详细信息”表中添加该产品的详细信息

在 CodeIgniter 的官方页面中,他们展示了如何做到这一点,但不使用函数,例如:

$this->db->trans_start(TRUE); // Query will be rolled back
$this->db->query('AN SQL QUERY...');
$this->db->trans_complete();

我需要使用函数并且仍然保持完整性,如果两个查询之一失败则不添加记录,我准备了以下代码,我想知道 CodeIgniter 是否能够通过这种方式检测查询失败或不撤消记录,或者是否有其他最佳实践或其他方式。

我没有使用$this->db->query('AN SQL QUERY...'),而是使用 功能:

public function init_product()
{
    $this->db->trans_begin();
    $this->new_product();
    $this->new_product_details();

    if ($this->db->trans_status() === FALSE)
        $this->db->trans_rollback();
    } else {
        $this->db->trans_commit();
    }
}

添加产品并返回聚合产品 ID:

public function new_product()
{      
    $data = array(            
        'name' => $this->input->post('name'),
        'details' => $this->input->post('details'),
        'price' => $this->input->post('price')
    );
    $this->db->insert('products', $data);
    if($this->db->affected_rows()) {            
        return $this->db->insert_id();
    }
    return false;
}

添加产品详细信息:

public function new_product_details()
{      
    $data = array(            
        'product_id' => $this->new_product(),
        'user_id' => $this->session->id_user
    );
    $this->db->insert('products', $data);
    if($this->db->affected_rows()) {            
        return true;
    }
    return false;
}

正如您指定的那样,我需要知道这种方式是否有效,即使我没有按照 CodeIgniter 中的示例进行操作,并且如果使用这些函数 CodeIgniter 可以检测数据库中的查询或插入是否失败,以及是否他们可以给我一些更好的例子。

【问题讨论】:

    标签: php mysql codeigniter transactions codeigniter-3


    【解决方案1】:

    为什么要这样做?不会工作。我看到你使用同一张表,所以为什么不在初始函数中执行此操作并在需要时返回插入 ID,如下所示:

    public function init_product()
    {
        $this->db->trans_begin();
    
        $data = array(            
            'name' => $this->input->post('name'),
            'details' => $this->input->post('details'),
            'price' => $this->input->post('price'),
            'user_id' => $this->session->id_user
        );
    
        $this->db->insert('products', $data);
    
        if ($this->db->trans_status() === FALSE)
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
    
        return $this->db->insert_id();
    }
    

    【讨论】:

    • 好主意,这也是一种实现方式,我想通过函数以最有条理的方式来实现它们
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多