Codeigniter 插入多对多连接 Table/Pivot Table

Codeigniter Insert into Many-to-Many Joining Table/Pivot Table

如果之前有人回答过这个问题,我深表歉意(如果有人能指出我将不胜感激),但我将如何插入多对多连接 table?

基本上我有一个基于体育赛事的比赛,因此有一个连接 table 来匹配 contest_id 到相关的 sports_events_id 。如果我要创建一个新的比赛,我将如何同时插入到 join table 数据库中?

或者,我是否必须先创建竞赛才能获得 contest_id,然后(并且只有在那时)将所有相关的 sports_events_id 插入连接 table?

感谢您提供的任何帮助和建议。

非常感谢。

解决方案

好的,所以我现在有以下解决方案可以插入连接 table

控制器

function add()
    {
        $this->form_validation->set_rules('contest_name', 'Contest Name', 'required|trim|xss_clean');

        if ($this->form_validation->run() == FALSE) {

            $data['view_file'] = 'add_contest';
            $this->load->module('template');
            $this->template->cmslayout($data);

        } else {

            $data1 = array(
                'contest_name' => $this->input->post('contest_name'),
            );

            $data2 = $this->input->post('game');

            if ($this->_transactions_new_contest($data1, $data2)) {
                return $query;
            }
            redirect('/contests/');
        }
    }

function _transactions_new_contest($data1, $data2) {
    $this->load->model('mdl_contests');
    $this->mdl_contests->_transactions_new_contest($data1, $data2);
}

型号

function _transactions_new_contest($data1, $data2){
    $this->db->trans_start();
    $this->db->insert('contests', $data1);
    $contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
    foreach ($contest_id->result() as $row) {
        $contest_result_id = $row->id;
        $this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $data2 . ')');
    }
    $this->db->trans_complete();
}

现在的问题是,如果我有多个 sports_events_id 或 post('game'),现在如何循环 $data2?

再一次,如果你能指出正确的方向,我将不胜感激。

要回答您的问题,您需要先插入到父 tables,然后使用父 table ID 作为外键引用插入从属 tables受抚养人 table.

你实际上暗示的是交易。数据库事务允许您以原子方式插入、更新、删除不同 table 中的行:要么它们全部工作并提交,要么如果一个失败它们全部回滚,以便您保持数据完整性。

CodeIgniter 支持 transactions