简体   繁体   中英

How to display results from two tables using JOIN in codeigniter?

So I have 3 tables that are going to be used for this problem.

Table Name: users

columns: USER_ID(INT & PRIMARY KEY), USER_EMAIL(VARCHAR)

Table Name: teams

columns: TEAM_ID(INT & PRIMARY KEY), TEAM_NAME(VARCHAR)

Table Name: user_teams

columns: USER_TEAM_ID(INT & PRIMARY KEY), USER_ID(INT & FOREIGN KEY from users ), TEAM_ID(INT & FOREIGN KEY from teams )

I am trying to display everyone's email or USER_EMAIL that is on a team.

For example:

Team 1

user with the USER_IDs 6 and 8 are on the team

TEAM_ID: 1

I want to echo the user's emails associated with those USER_IDs on Team 1.

I feel that I would have to use a JOIN to make this happen but am unsure of how to go about doing it with codeigniter.

Any help is appreciated, thank you.

This is actually pretty straight forward. In your model,

$this->db->select('users.USER_EMAIL')
->from('users')
->join('user_teams', 'users.USER_ID = user_teams.USER_ID')
->join('teams', 'teams.TEAM_ID = user_teams.TEAM_ID')
->where('teams.TEAM_ID', $teamID); //In your case 1 here
$query = $this->db->get();
return $query->result_array();

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