【问题标题】:codeigniter auto increment foreignkeycodeigniter 自动递增外键
【发布时间】:2016-09-06 12:56:17
【问题描述】:


在我的应用程序中,我具有向 mysqldb 插入数据并为一条新闻提供更多一张图片的功能,在数据库中,我将新闻 id 作为上传表中的外键,所有插入工作正常,但问题新闻 FK 在当我插入数据时上传表插入的第一行取我设置的值,另一行取自动递增,所以接下来你找到代码:
上传表中插入的数据

当您看到正确的数据是行的 id 为 31 时,另一个是自动增量
我插入的代码;
控制器

    public function insertNews() {
    $this->do_one_upload();
        $this->load->model('newsModel');
        $this->load->model('fileModel');
        $ad_ne_data = array(
                'titel' => $this->input->post('ad_news_title') ,
                'content' => $this->input->post('ad_news_content') ,
                'news_category_id' => $this->input->post('ad_news_category') ,
                'img_url' => $this->do_one_upload()[1]['full_path'],
                'created_at' => date("Y-m-d")
        );

        $this->newsModel->addNews($ad_ne_data);
        $i=0;
        while($i < count($this->do_one_upload())) {
            // var_dump($this->do_one_upload());
            $ad_imgs_news =array(
                'title' => $this->do_one_upload()[$i]['client_name'],
                'file_path' => $this->do_one_upload()[$i]['full_path'],
                'type' => $this->do_one_upload()[$i]['file_type'],
                'size' => $this->do_one_upload()[$i]['file_size'],
                'img_news_id' => $this->newsModel->getLastNewsId()
            );
             $i++;
            $this->fileModel->addUpload($ad_imgs_news);
            var_dump($ad_imgs_news);
        }
}


新闻模型
获取最后插入的新闻 id ;

    public function getLastNewsId()
    {
      $last_id = $this->db->insert_id();
      return $last_id;
    }

上传模型中的上传插入方法

    public function addUpload($data)
    {
      // $this->db->set('name', $name);
      $this->db->insert('upload', $data);
    }


那么问题出在数据库或代码中还是???
谢谢,
问候

【问题讨论】:

    标签: php mysql codeigniter insert auto-increment


    【解决方案1】:

    尝试返回

    $last_id = $this->db->insert_id();
    

    来自

    $this->newsModel->addNews($ad_ne_data);
    

    addNews函数中查询后立即获取insert_id。

    【讨论】:

    • 很高兴。总是乐于提供帮助。
    猜你喜欢
    • 2016-04-22
    • 1970-01-01
    • 2015-11-13
    • 2012-02-15
    • 1970-01-01
    • 2023-03-26
    • 2013-09-28
    • 2019-09-26
    • 2017-02-10
    相关资源
    最近更新 更多