Activerecord Codeigniter:从多个表中选择

Activerecord Codeigniter:从多个表中选择,activerecord,select,codeigniter,Activerecord,Select,Codeigniter,如何从两个或多个表中选择行 我正在为表单设置默认字段,我需要两个表中的值 我目前的代码是: $this->CI->db->select('*'); $this->CI->db->from('user_profiles'); $this->CI->db->where('user_id' , $id); $user = $this->CI->db->get(); $user = $user

如何从两个或多个表中选择行

我正在为表单设置默认字段,我需要两个表中的值

我目前的代码是:

    $this->CI->db->select('*');
    $this->CI->db->from('user_profiles');
    $this->CI->db->where('user_id' , $id);
    $user = $this->CI->db->get();
    $user = $user->row_array();
    $this->CI->validation->set_default_value($user);


通过这种方式,您可以添加第三个名为c的表,并向sql命令中添加“and”命令。

只需将另一个表添加到“->from()”方法中即可。比如:

 $this->db->select('t1.field, t2.field2')
          ->from('table1 AS t1, table2 AS t2')
          ->where('t1.id = t2.table1_id')
          ->where('t1.user_id', $user_id);

用户指南中的示例应解释这一点:

$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');

$query = $this->db->get();

// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id
$this->db->select('*');//db->from('blogs');
$this->db->join('comments','comments.id=blogs.id');
$query=$this->db->get();
//产生:
//从博客中选择*
//在comments.id=blogs.id上加入评论

请参阅《用户指南》第页下的全部内容。

我认为语法不正确。
您需要选择一条记录。我有两个表,一个表的id通过参数传递,以及两个表之间的关系。

我认为问题不在于连接,而在于如何显示两个不同表中的值-用户指南似乎没有解释这一点

以下是我的看法:

    $this->db->select('u.*, c.company, r.description');
    $this->db->from('users u, company c, roles r');
    $this->db->where('c.id = u.id_company');
    $this->db->where('r.permissions = u.permissions');
    $query = $this->db->get();
试试这个

   $this->db->select('*')
            ->from('student')
            ->where('student.roll_no',$id)
            ->join('student_details','student_details.roll_no = student.roll_no')
            ->join('course_details','course_details.roll_no = student.roll_no');
   $query = $this->db->get();
   return $query->row_array();
//从表1中选择所有字段,从表2中选择一个或多个字段


我是个大笨蛋。你能再解释一下吗?这不是一种运行查询的活动记录方式。根据文档,是的,这是一种在CodeIgniter中执行联接操作的方式,会产生错误的语法。我不这么认为。您能详细说明一下吗?该语法仅在php5中受支持。用户指南中的示例似乎没有从第二个表中生成字段。您是如何做到的?*=所有可用表格中的所有内容。如果它不出现,你就做错了。另外,如果在不同的表中有两个同名字段,则只会显示一个字段。你需要做
foo-as-bar
来获得
->bar
这正是我需要看到的。不确定逗号分隔的字符串或具有多个值的数组是否是正确的语法。如果需要记录集,可以这样做:return$this->db->get()->result();
   $this->db->select('*')
            ->from('student')
            ->where('student.roll_no',$id)
            ->join('student_details','student_details.roll_no = student.roll_no')
            ->join('course_details','course_details.roll_no = student.roll_no');
   $query = $this->db->get();
   return $query->row_array();
$this->db->select('table1.*, table2.name');
    $this->db->from('table1, table2');
    $this->db->where('table2.category_id = table1.id');
    $this->db->where('table2.lang_id',$id); // your where with variable
    $query = $this->db->get();
    return $query->result();