【问题标题】:How to Run a Custom update query in codeigniter如何在 codeigniter 中运行自定义更新查询
【发布时间】:2017-05-23 06:10:35
【问题描述】:

是否可以在 codeigniter 中运行自定义更新查询。我需要在 codeigniter 中运行以下查询,

UPDATE `category` SET `online`= IF(online=1,0,1) WHERE id = 10

在更新前检查在线值。 if online = 1 then 0, if online = 0 then 1. 我测试并且查询工作正常,但是我如何在 codeigniter 中运行这个查询。

【问题讨论】:

  • 在模型上使用$this->db->query( $your_query )
  • 是的,它正在工作
  • 其实,为了简单起见,我更喜欢用这个。我们可以测试查询,然后将其复制到模型:)

标签: mysql codeigniter activerecord


【解决方案1】:

尝试使用

    $updateData = array(
        'online' => IF(online=1,0,1)
    );
    $this->db->where('id', 10);
    $this->db->update('category', $updateData);

【讨论】:

  • can't put 'online' => IF(online=1,0,1) 出错了
  • 用单引号标出online' =>'IF(online=1,0,1)'
【解决方案2】:

你可以像 Nishant Nair 提到的那样做,或者你可以使用纯 SQL,比如:

$this->db->query('YOUR SQL QUERY HERE');

还可以查看文档: https://www.codeigniter.com/userguide3/database/query_builder.html#updating-data

【讨论】:

    【解决方案3】:
        $updateData = array(
            'col1' => 999
        );
        $this->db->set("online","IF(online=1,0,1)",false); //set false third parameter to prevent from auto escaping
        $this->db->where('id', 10);
        $this->db->update('category', $updateData);
    

    您可以在 codeigniter db query helper 中使用set 命令。如果您需要更多set 字段,您仍然可以在update 命令第二个参数中使用updateData array

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 2019-06-27
      • 2017-11-06
      • 1970-01-01
      • 2014-06-05
      • 2019-07-28
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多