我想显示来自table_one的数据,其中tableone_id包含在table_two..which是一对多的关系。这是一个例子。
table_one table_two
id | name id | name |tableone_id
1 | A 1 | C | 1
2 | B 2 | D | 1
3 | E | 2
4 | F | 2
我期待PHP的结果是......
Number | Name | Linked Item |
1 | A | C |
| | D |
2 | B | E |
| | F |
我已经尝试了一些像
这样的代码**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();
foreach($head as $key => $value)
{
$head[$key]['items'] = $this->db->query("SELECT
a.id,
b.id,
b.name as tabletwo_name,
FROM table_one a
JOIN table_two b on a.id = b.id
where b.id =".$value['id'])->result_array();
}
我做的代码,fails.how我为那个案例做了正确的代码吗? 谢谢
答案 0 :(得分:0)
将您的第一个查询更改为:
$this->db->query("SELECT table_one.id as number, table_one.name as name, table_two.name as linked_item FROM table_one LEFT JOIN table_two ON table_one.id = table_two.tableone_id")->result_array();
然后就这样做:
foreach($head as $key => $value)
{
$head[$key]['items'] = $value;
}
答案 1 :(得分:0)
尝试这个,嗯,我没有测试过,但你可以
$this->db->select('table_one.name AS t1,table_two.name AS t2');
$this->db->join('table_two', 'table_two.tableone_id=table_one.id');
$rs = $this->db->get('table_one');
$count = 1;
$data = array();
foreach ($rs->result() as $key => $value)
{
$data[] = array(
'number' => $count ++,
'name' => $value['t1'],
'linked_item' => $value['t2']
);
}
print_r($data);
答案 2 :(得分:0)
控制器用于在codeigniter中进行模型和视图之间的通信。所以你的数据库查询应该在模型中。
根据您的查询制作模型,也许您可以尝试这样:
function something(){
$qry = 'a.* , b.tableone_id';
$this->db->select($qry);
$this->db->from('table_one as a');
$this->db->join('table_two b', 'b.tableone_id = a.id', 'left');
$q = $this->db->get();
return $q;
}
尝试按照此链接获取有关CI中数据库引用的更多参考: https://www.codeigniter.com/userguide3/database/query_builder.html