【问题标题】:Fixing Codeigniter Active Record update query修复 Codeigniter Active Record 更新查询
【发布时间】:2014-02-07 17:29:15
【问题描述】:

这是一个在 Codeigniter 应用中处理模型的类

class MY_Model extends CI_Model {

    const DB_TABLE = 'abstract';
    const DB_TABLE_PK = 'abstract';

    private function update() {
        $this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK);
    }
    public function save() {
        if (isset($this->{$this::DB_TABLE_PK})) {
            $this->update();
        }
        else {
            $this->insert();
        }}

这是从上述类扩展而来的模型:

class Projects extends MY_Model {

    const DB_TABLE = 'projects';
    const DB_TABLE_PK = 'project_id';


    public $project_id;
    public $project_name;
    public $project_investment;
    public $project_employment;
    public $project_province;
    public $project_city;
    public $project_address;
    public $project_estimate;
    public $project_duration;
    public $project_construction;
}

根据 Codeigniter 用户指南,我认为更新查询的第三个参数存在问题(它只是发送 DB_TABLE_PK 名称,在本例中为 'project_id')但由于我是 OOP 新手,不知道如何修复它。

Codeigniter 用户指南:

$this->db->update('mytable', $data, "id = 4");

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    上面的函数好像没有update()的完整WHERE语句

    $this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK); 
    

    会翻译成

    UPDATE $this::DB_TABLE SET $this WHERE $this::DB_TABLE_PK
    

    在上面的示例中,$this::DB_TABLE_PK 是键的名称 ('project_id'),而不是它的值。

    我会坚持

    $this->db->where($this::DB_TABLE_PK, $pk)->update($this::DB_TABLE, $this);
    

    其中 $pk 是 PRIMARY KEY 的实际值

    【讨论】:

    • 这正是我的意思。但是在 OOP 编程中我应该写什么而不是 $pk 呢?
    【解决方案2】:

    guide clrearly says

    $data_array = array();
    $where_array = array();
    $this->db->update('table_name', $where_array, $data_array());
    

    例子

    $data_array = array('name' => 'Alpha', 'gender' => 'male'); // change column name to "Alpha", and gender column to 'male'
    $where_array = array('id' => '4', 'allowed' => '1'); // update row with $data_array where id = 4 and allowed = 1
    $this->db->update('person', $where_array, $data_array());
    

    我强烈建议您使用 profiler $this->output->enable_profiler(TRUE); 将其放在控制器中的任何位置,在您的页面下将有“profiler”显示发布/获取数据查询、会话和所有有用的信息。

    【讨论】:

    • 而我的问题是如何在OOP方法中写入这个id值(4)?
    • 你必须使用array()结构,或者你写的$this->db->update('mytable', $data, "id = 4");。在这一点上,我想我不完全理解你的问题。
    【解决方案3】:

    我修好了:

    private function update() {
        $value=$this::DB_TABLE_PK;
        $this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK.' = '.$this->$value);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 2013-02-22
      • 1970-01-01
      • 2016-03-15
      • 2013-01-09
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2017-02-26
      相关资源
      最近更新 更多