【问题标题】:How to replace update SQL query to CodeIgniter ActiveRecord?如何将更新 SQL 查询替换为 CodeIgniter ActiveRecord?
【发布时间】:2016-03-25 07:09:55
【问题描述】:

我使用 CodeIgniter 框架。当我尝试使用 Active Record 更新数据库时,我遇到了问题。 我发现了如何通过原始 SQL 来解决它。

UPDATE articles_articlegroups
  SET isDeleted = 1
    WHERE articlegroupId IN (
      SELECT id
      FROM articlegroups
      WHERE parent_id = $catID
      )

但我需要使用 AR。

我用文章划分类别和子类别。类别和子类别在一张表中。与parent_id. 链接 文章链接在一对多表中,因为它可以属于不同的类别。

想删除所有文章,只知道parent_id.

【问题讨论】:

    标签: php mysql codeigniter activerecord


    【解决方案1】:
    $data = array(
     'isDeleted' => 1
     );
     $this->db->set($data); 
     $this->db->where(
        'articlegroupId IN (
                           SELECT id
                            FROM articlegroups
                            WHERE parent_id = '.$catID.'
                           )'
                       );\
     $this->db->update('articles_articlegroups');
    

    【讨论】:

    • 谢谢,我阅读了文档并找到了带有子查询的解决方案。 select()...->get_compiled_select() 和 where_in();
    【解决方案2】:

    就这样试试吧,

    $this->db->query("your query here");
    

    最终查询

    $this->db->query("UPDATE articles_articlegroups
          SET isDeleted = 1
          WHERE articlegroupId IN (
                                  SELECT id
                                  FROM articlegroups
                                  WHERE parent_id = $catID
                                  )");
    

    【讨论】:

    • 是的,我做到了。但我需要用 $this->db->update() 替换它
    • $this->db->query() 将执行您的更新查询。 $this->db->update()使用时不需要$this->db->query()
    • 好的。但是如何使用$this->db->where()、$this->db->update()、$this->db->set()等方法呢?
    • 无需使用所有这些 AR。当您使用->query() 时,将普通查询作为参数传递。 CI 会自动执行查询。
    【解决方案3】:

    最简单快捷的方法是通过$db->query("sql") 进行操作

      $sql= "UPDATE articles_articlegroups
      SET isDeleted = 1
      WHERE articlegroupId IN (
                              SELECT id
                              FROM articlegroups
                              WHERE parent_id = $catID
                              )";
      $this->db->query($sql);
    

    但是不要直接传参数,避免sql注入,绑定sql字符串中的params。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多