[英]Codeigniter merge into one row record with sql one to many relationship
I would like to query one to many relationship 我想查询一对多关系
eg: 例如:
Table A: Table B:
id | country_name id | name | table_A_id
1 | Usa 1 | kerry | 1
2 | Australia 2 | jerry | 1
3 | tommy | 2
4 | cherry | 2
my purpose is to query the result to merge one row record 我的目的是查询结果以合并一行记录
eg: result list: 例如:结果列表:
1 Record 2 Record
Usa Australia
kerry tommy
jeryy cherry
Currently, I am using Codeignter framework and beginner for sql, please don't mind me guys. 当前,我正在使用Codeignter框架和sql初学者,请不要介意我。
$this->db->select('*')
>from("table A")
->join("table B", "table.A.id = table_A_id");
$query = $this->db->get();
if($query->num_rows() > 0) {
return $query->result();
}
My view 我的观点
<?php foreach($posts as $post) {
echo $post->country_name;
echo $post->name;
} ?>
However, it gives me 4 row records. 但是,它给了我4行记录。
1 Record 2 Record
Usa Usa
kerry jerry
3 Record 4 Record
Australia Australia
tommy cherry
Thanks you guys in advance for helping me. 预先感谢你们对我的帮助。
Here is what you missed 这是你错过的
$this->db->select('*')
>from("table A")
->join("table B", "table.A.id = table_A_id");
$query = $this->db->get();
if($query->num_rows() > 0) {
return $query->result();
}
it should have been 应该是
->join("table B", 'B.table_A_id=A.id');
hope this make sense 希望这有意义
option B 选项B
$this->db->join('table B','B.table_A_id=A.id','INNER');
$query = $this->db->get('table A');
Try out this 试试这个
SELECT country, group_concat(name) FROM city c INNER JOIN employee e
ON c.id = e.city_id group by c.id
output 产量
('USA ' , 'jerry ,kerry'),
('Australia', 'cherry ,tommy');
My solution found without using inner join: 我的解决方案发现不使用内部联接:
public function mergeRecord() {
$array_store = array();
foreach($this->one() as $row) {
$child = $this->many($row['id']);
if($child) {
$return = array_merge(array("parent" => $row), array("child" =>$child));
array_push($array_store, $return);
}
}
return $array_store;
}
public function one() {
$query = $this->db->select("*")
->get("table A")
->result_array();
return $query;
}
public function many($id) {
$query = $this->db->select("id, name")
->where("table_A_id", $id)
->get("table B")
->result_array();
return $query;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.