【问题标题】:how to update data from relation many to many table using codeigiter如何使用codeigniter更新关系多对多表中的数据
【发布时间】:2018-03-29 16:32:30
【问题描述】:

我的控制器

public function edit($id=''){

        $data['post'] = $this->posts->getpostbyid('posts',$id);
        $data['c'] = $this->posts->categories_post($id);
}

public function update()
    {
      $id = $this->input->post('id');
      $categories = $this->input->post('category');
      foreach ($categories as $category) {

            $data = array(
                'idcategory' => $category
            );
            $this->posts->updatepost('categories_detail', $data,$id);

        }

我的模型

public function updatepost($table,$data,$id)
    {
        $this->db->where('idpost', $id);
        return $this->db->update($table, $data);
    }
public function categories_post($id)
    {
        $this->db->select('categories.idcategory, categories.category_name');
        $this->db->from('categories');
        $this->db->join('categories_detail', 'categories_detail.idcategory = categories.idcategory', 'inner');
        $this->db->join('posts', 'posts.idpost = categories_detail.idpost', 'inner');
        $this->db->where('posts.idpost', $id);
        return $this->db->get()->result_array();
    }

我的观点

<input type="hidden" value="<?php echo $post['idpost'] ?>" name="id">
<?php
    foreach ($categories as $data) { ?>
       <div class="form-group">
          <input <?php foreach ($c as $cc) { echo $data->idcategory == $cc['idcategory'] ? 'checked' : ''; } ?> type="checkbox" name="category[]" value="<?php echo $data->idcategory ?>">&nbsp;&nbsp;<?php echo $data->category_name ?>
       </div>
<?php } ?>

就我而言,我有一个多对多数据库的关系;

  1. 帖子:idpost、帖子。
  2. 类别:idcategory、category_name
  3. categories_detail:id,idpost。 idcategory

问题是当我更新类别时,它只是插入 1 个类别,即使我检查了 2 个或更多类别。 我该如何解决这个问题?

【问题讨论】:

  • id 的名称属性在哪里设置?你正在更新where idpost = id,但我没有看到它被发布在任何地方,所以$this-&gt;input-&gt;post('id') would be null`
  • 此外,您似乎只会在同一 id 上更新 categories_detail
  • 在视图中 -> 编辑帖子。我将其设置为 type="hidden"
  • 我刚刚在视图中更新了我的代码
  • 你只发了一个id,所以你在重复更新同一个id

标签: php codeigniter


【解决方案1】:

您正在使用帖子id 更新category_details 表,这将影响所有类别。对于多对多关系,在categories_detail 表中不需要id

如果您想以简单的方式更新categories_detail 表中的帖子类别。只需使用idpost表格categories_detail表删除特定帖子的所有数据并插入新的idpostidcategory

由于多对多关系更新多对多表中的列(在本例中为categories_detail 表)非常复杂且不适合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-16
    • 2011-12-01
    • 2018-05-31
    • 1970-01-01
    • 2022-01-27
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多