如何在codeigniter PHP中加入2个表?

时间:2017-06-05 07:30:06

标签: codeigniter

我有2个表guest_info和guest_profile.two列有g_uid和company_id.Based on company_id(我有companyID),我必须采取所有g_uid。 在guest_info表中,

g_uid | companyID

1 5

2 5

3 6

在guest_profile表中,显示此表中的所有值(只需显示前两个数据)

g_uid | FNAME

1 xyz

2 fds

3 fsdf

3 个答案:

答案 0 :(得分:1)

转到文件夹“模型”这是您对数据库执行所有CRUD操作的地方。 例如,您可以创建名为“guest_profile_model.php”的模型文件

现在打开该文件并粘贴下面的代码:

       <?php

    class guest_profile_model extends CI_Model {

public function select($company_id) {

$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
 $result = $this->db->query($query); 

 return $result->result_object();
}
    }

就是这样,现在从你的控制器中你只需要加载并调用它。 例如:

  $this-> load-> model('guest_profile_model ');
    $company_id = 1;
    $queryResult = $this -> guest_profile_model ->select(company_id);

    print_r($queryResult);

请注意,查询返回将是一个对象,这是因为模型中的“result_object”,如果您愿意,可以将其更改为数组。

答案 1 :(得分:0)

//Try this sql query to join 2 table in codeigniter
$company_id = 5;
$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");

答案 2 :(得分:-1)

$this->db->select('*');
$this->db->from('Table1 AS a');
$this->db->join('Table2 AS b', 'a.id = c.id', 'LEFT');
$this->db->join('Table3 AS c', 'a.name = c.name', 'LEFT');
$result = $this->db->get();
希望你能得到我的榜样 更多信息:https://www.codeigniter.com/userguide3/database/query_builder.html?highlight=joins#selecting-data