简体   繁体   中英

Getting data from three tables codeigniter using Query builder

I have three tables in database.

1.george_holiday_users(id,package_id,name,email)

2.george_holiday_passengers(id,user_id,type,name,age,gender)

3.george_packages (id,package_name,description)

Now i want to select data from three tables george_holiday_users,george_packages and george_holiday_passengers tables where george_holiday_users.id=george_holiday_passengers.user_id and george_holiday_users.package_id=george_packages.id

    $this->db->select('*');
           $this->db->from('george_holiday_users');
           $this->db->join('george_holiday_passengers', 'george_holiday_users.id = george_holiday_passengers.user_id');
           $this->db->join('george_packages', 'george_packages.id = george_holiday_users.package_id');
           $query = $this->db->get();
return $query->result();

But i will the data from only george_holiday_users table.

My opinion is that you can remove the george_holiday_passengers and add the type,age,gender columns to the george_holiday_users as looking to it; its only a extended data of the holiday_users table and build query with your new database tables.

$query = $this->db->select('u.*, p.package_name, p.description')
       ->from('george_holiday_users u')
       ->join('george_packges p', 'u.package_id = p.id', 'left')
       ->get();

return $query->result();

anyway, you can achieved the result using this query.

$query = $this->db->select('u.*, hp.type, hp.name AS passengers_name, hp.age, hp.gender, p.package_name, p.description')
       ->from('george_holiday_users u')
       ->join('george_holiday_passengers hp', 'hp.user_id = u.id', 'left')
       ->join('george_packges p', 'u.package_id = p.id', 'left')
       ->get();

return $query->result();

you should be careful about the column names because on your database there are a lot of columns with the same names, It might affect your query when your using joins, etc.

Hope that helps.

Try this

$query = $this->db->select("SELECT * 
                FROM george_holiday_users 
                INNER JOIN george_holiday_passenger ON george_holiday_users.id = george_holiday_passengers.user_id
                INNER JOIN george_packages ON george_holiday_users.package_id = george_packages.id");
$result = $query->result_array();
return $result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM