codeigniter foreach具有相同ID的多个条目

时间:2017-09-02 13:06:05

标签: php mysql codeigniter

我尝试向特定团队中的用户展示。我的问题是,我可以向所有用户显示,但不仅仅是显示特定的team_id。如果我查看我的网站domain.com/teams/1,我想只查看team_id 1

中的用户

也许你可以帮助我,我需要在这一行改变

$data['users'] = $this->db->get('users')->result();

我只从用户team_id获得用户。

我有两个sql表

表用户

user_id username team_id

   1     paul      1
   2     tom       2
   3     brad      1
   4     pim       2

表团队

team_id   teamname

  1         team1
  2         team1

现在我尝试将保罗和布拉德视为第一队,将tom和pim视为第二队。

控制器

public function index($id) {
        $data = array();
         if ($id) {
            $this->{$this->model}->{$this->_primary_key} = $id;
            $this->{$this->model}->order_by['teams_id'] = 'DESC';


            $data['users'] = $this->db->get('users')->result();


            $data['item'] = $this->{$this->model}->get();
            $this->load->view($this->module, $data); 
            if (!$data['item'])
                show_404();
         }

    }

查看domain.com/teams/1

<?php foreach ($users as $item): ?>
     <?php echo $item->username ?>
<?php endforeach ?>

2 个答案:

答案 0 :(得分:0)

公共职能指数($ team_id = 0)  {

 $data=array();
 if($team_id > 0)
 {
    $data['team_users'] = $this->Team_modal->getTeamUsers($team_id);
 }

  $this->load->view('showTeam',$data);

  /*

  if you want to print data then :
  if(count($data['team_users']) > 0){
          foreach($data['team_users'] as $row){
             echo"user_id =".$row['user_id']."  username =".$row['username']."  team_id =".$row['team_id']."<br>";
          }
      }
      else{
        echo"Oops no data for rquested team id..";
      }
  */

}

在模特:

public function getTeamUsers($ team_id) {

$this->db->select('user_id,username,team_id');
$this->db->where('team_id',$team_id);
return $this->db->get('table_name')->result_array();

}

答案 1 :(得分:0)

你可以在get之前拨打电话:

$this->db->where('team_id', $id);
$data['users'] = $this->db->get('users')->result();
相关问题