phpmysqlcodeigniterquery-builderwhere-in

Build CodeIgniter query from the results of another query


I have the following CI query builder query

$query_teams = $this->db->get_where('teams_in_cups', array('cup_id' => 2));
$team_ids = $query_teams->result_array();

I want $team_ids (which currently outputs two ids -> 22 and 25) to be compatible with the following query:

$this->db->where_in('id', $team_ids);    
$query_team_details = $this->db->get('teams');

In the second query, $team_ids should look like the following array(22,25);

I tried foreach(), implode(), explode(), but couldn't manage to get it to work.


Solution

  • You can use MySQL join to get the desired result.

    I am fixing your current situation only.

    $query_teams = $this->db->get_where('teams_in_cups', array('cup_id' => 2));
    $team_data=$query_teams->result();
    team_ids='';
    foreach($team_data as $td)
    {
       $team_ids=$team_id.','.$td->team_id;
    }
    $team_ids=ltrim($team_ids,',');
    $this->db->where_in('id', $team_ids);    
    $query_team_details = $this->db->get('teams');