【问题标题】:What is wrong with this Code Igniter mySQL query?这个 Code Igniter mySQL 查询有什么问题?
【发布时间】:2012-01-19 18:37:14
【问题描述】:

我有两个用于存储用户信息的表。一种是用于身份验证,另一种是用户将自己输入的信息。我正在编写一个模型,当用户与此信息交互时将使用该模型。下面的方法是返回数据进行显示和修改。

我需要一个查询,它将从 $accounts_table 返回“电子邮件”和“用户名”,从 $profiles_table 返回 *。不过,我似乎无法理解 JOIN 语法。我了解连接的工作原理,但我的查询会引发语法错误。

function get_userdata($id){
     $data = array();

     $this->db->get_where($this->profiles_table, array('user_id' => $id));
     $this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
     $data= $this->db->get();

     return $data;
}

【问题讨论】:

  • 你能发布错误信息吗?
  • 我终于让查询完成了它应该做的事情,但我不得不直接使用 mySQL:function get($id) { $record=$this->db->query(' SELECT '.$this->profiles_table.'.*, '.$this->accounts_table.'.username, '.$this->accounts_table.'.email FROM '.$this->profiles_table.' LEFT JOIN '.$this->accounts_table.' ON '.$this->profiles_table.'.user_id = '.$this->accounts_table.'.id WHERE '.$this->profiles_table.'.user_id = '.$id); return $record->row_array(); } 这将如何在 CI 表示法中链接起来......为了胜利?

标签: mysql codeigniter


【解决方案1】:

我发现了几个问题:

您应该使用 $this->db->where(),而不是 $this->db->get_where()。 get_where() 立即执行查询。

$this->db->get_where('user_id', $id);

$this->db->join() 的第一个参数也只能是表名,不包括字段。

$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');

您返回的 $data 只是一个空数组 ()。您需要像这样将查询结果传递给 $data:

$data = $record->result_array();

【讨论】:

    【解决方案2】:

    get_where 执行查询。所以,你的 join 是它自己的查询,这是行不通的。

    您需要将get_where 分解为where 和from。

    另外,在 MySQL 中,JOIN 是一个表,而不是一个字段。如果您想要该字段,请将其添加到 SELECT。

    $this->db->select($this->profiles_table.'.*');
    $this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
    $this->db->from($this->profiles_table);
    $this->db->where('user_id', $id);
    $this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
    $data = $this->db->get();
    

    注意:$this->db->get() 返回一个query object,您需要使用result 或row 来获取数据。

    【讨论】:

      【解决方案3】:

      我认为你错了:

       $this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
      

      第一个参数应该是表格而不是字段:$this->accounts_table.'.email' 恕我直言是错误的。或者只是一个错字:)

      【讨论】:

        猜你喜欢
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多