PHP 关系查询

PHP relationship query

我正在使用 PHP & jamierumbelow/codeigniter-base-model 我有两张桌子

Table 1: Class
classId  classStd
-----------------------
1         Prep
3         NUR
4         STD-1
5         STD-2

Table2: Section
sectionId  classId  section  sectionName
---------------------------------------------------
5            1       A         rose
6            1       B         red
7            1       C         green
8            3       A         ROME
9            3       B         PARIS

关系是:一个Class可以有很多段。 我的函数

函数section_get(){

$this->load->model('Model_section');
// this return all section with its classSTD name correctly
$pages = $this->Model_section->with('class')->get_all();
$this->response($pages);

}

Return 关注

[
    {"sectionId":"5","classId":"1","section":"A","sectionName":"rose","class":{"classId":"1","classStd":"Prep"}},
    {"sectionId":"6","classId":"1","section":"B","sectionName":"red","class":{"classId":"1","classStd":"Prep"}},
    {"sectionId":"7","classId":"1","section":"C","sectionName":"green","class":{"classId":"1","classStd":"Prep"}},
    {"sectionId":"8","classId":"3","section":"A","sectionName":"ROME","class":{"classId":"3","classStd":"NUR"}},
    {"sectionId":"9","classId":"3","section":"B","sectionName":"PARIS","class":{"classId":"3","classStd":"NUR"}}
]

如何只获取特定记录,例如 where “classId = 1”

使用get_many_by方法:

$pages = $this->Model_section->with('class')->get_many_by('classId',1);

或者您可以执行以下操作,创建一个带连接的 dB 查询,获取您需要的所有信息,然后按 groupID

对结果进行分组