我在数据库中有3个表:
团队
- id
- 名称
匹配
- id(int)
- team_home_id
- team_away_id
目标
- id
- match_id
- team_id
- 时间
我需要在控制器中获得目标的情况下显示团队的名称。
我知道我应该做联接表。
我有此代码:
public function get_goals() {
$this->db->select('goals.*');
$this->db->from('goals');
$this->db->join('matches', 'matches.id = goals.match_id');
$q = $this->db->get();
return $q->result();
}
我不知道接下来要怎么做。
我在视图显示名称中需要:
$ goals-> team_home_name 和 $ goals-> team_away_name
答案 0 :(得分:1)
您可以尝试以下操作:-
public function get_goals() {
$this->db->select('g.* , t.name as team_home_name , t.name as team_away_name);
$this->db->from('goals as g');
$this->db->join('matches as m', 'm.id = g.match_id');
$this->db->join('teams as t', 't.id = g.team_id');
$q = $this->db->get();
return $q->result();
}
答案 1 :(得分:1)
要获得$goals->team_home_name
和$goals->team_away_name
的结果,请使用如下别名:
public function get_goals() {
$this->db->select('goals.*, home_team.name team_home_name, away_team.name team_away_name');
$this->db->from('goals');
$this->db->join('matches', 'matches.id = goals.match_id');
$this->db->join('teams home_team', 'home_team.id = matches.team_home_id');
$this->db->join('teams away_team', 'away_team.id = matches.team_away_id');
$q = $this->db->get();
return $q->result();
}
答案 2 :(得分:0)
U可以使用别名
从“团队”表中获取team_away_name和team_home_name
public function get_goals() {
$this->db->select('goals.*, team.team_home_name, team.team_away_name');
$this->db->from('goals');
$this->db->join('matches', 'matches.id = goals.match_id');
$this->db->join('teams as team', 'team.id = goals.team_id');
$q = $this->db->get();
return $q->result();
}