如何使用 Codeigniter my_model class 进行多个 where 条件的更新?

How can use Codeigniter my_model class for udate with multiple where condetion?

我使用 codeigniter my_model class 来更新我的 table 数据。

实际我需要查询的是

`UPDATE `pay_project` SET `awarded` = '129' WHERE `pay_id` = 1 and `status` ='y'

为此,我尝试了 codeignter my_model 函数更新

$this->pay_project_model->update_by(array('pay_id'=>1,'status'=>'y'),$updateJob);

但是代码无法正常工作,如果当时我尝试使用 update() 而不是 update_by(),它的显示如下

`UPDATE `pay_project` SET `awarded` = '129' WHERE 'id'=array()

请帮我解决这个问题?我也在尝试使用 update_many(),同样不起作用..

使用的模型是 https://github.com/jamierumbelow/codeigniter-base-model

这是您在模型函数中需要的查询。

class my_model extends CI_Model {

    function __construct(){
        parent::__construct();
    }

    /*Model function*/
    function update_by($condition = array(),$updateJob=array())
    {
        if($condition && $updateJob)
        {
            $this->db->where($condition);
            $this->db->update('pay_project', $updateJob );
        }

    }
}

现在您可以将控制器中的现有代码用于您想要的目的。

$updateJob = ['awarded' => '129'];
$this->pay_project_model->update_by(array('pay_id'=>1,'status'=>'y'), $updateJob);

试试这个 Active Records,它会让你知道你在做什么以及查询

function update($data = array(), $where = '') {
    $where = array('pay_id'=>1,'status'=>'y');
    $data = array('awarded' => '129');
    $this->db->where($where);
    $res = $this->db->update($this->main_table, $data);
    $rs = $this->db->affected_rows();
    return $rs;
}

使用这个

$query = $this->db->query("UPDATE pay_project SET awarded = '129' WHERE pay_id = '1' and status ='y' ");
$result = $query->result_array();
return $result;

使用此 codeigniter 活动记录进行数据库操作

$data = array(
           'awarded' => '129'
        );
$where = array(
          'pay_id'=>1,
          'status'=>'y'
         );

$this->db->where($where);
$this->db->update('pay_project', $data); 

有关文档,请参阅此 link codeigniter active records update

如果您使用的是 Codeigniter My_model class,那么您需要像这样更改您的模型才能使用 update_by() 函数

class Pay_project_model extends MY_Model {
protected $table='pay_project';
function update_by($where = array(),$data=array())
 {
        $this->db->where($where);
        $query = $this->db->update($this->table,$data);
        return $query;
  }
}

在My_modelclass中没有默认选项可以通过多个where条件更新class,所以你需要写update_by()函数。将函数简单复制粘贴到您的 class 中,这将完美运行。