php - Codeigniter:查询数据库返回多个结果
问题描述
我正在尝试查询在两个表之间建立连接的数据库。
特别是我有一个讲解员列表,每个讲解员都有一个带有数据的议程,并且时间穿插在一个小时内。所以例如在表中
议程
id | docent_id | date | start | end |
1 | 1 | 2020-05-29 | 09:00 | 10:00 |
2 | 1 | 2020-05-29 | 10:00 | 11:00 |
3 | 2 | 2020-05-29 | 09:00 | 10:00 |
所以我在我的控制器中有:
public function docent_get()
{
$this->load->model('Docent_model');
$result = $this->docent_model->getDocent();
if (is_null($result)) {
$this->response(null, 404);
return;
}
$this->response($result, 200);
}
在我的模型中:
public function getDocent()
{
$roles = 'Docent';
$query = $this->db->select('Persons.id, Persons.name, Persons.surname, Agenda.date, Agenda.start_at, Agenda.end_at')
->from('Persons')
->join('Agenda', 'Persons.id = Agenda.docent_id', 'INNER')
->where('Agenda.free', 'true')
->where('roles', $roles)
->get();
return $query->result();
现在这个查询可以工作了,但是这个查询的结果是一个由三个组成的数组,其中具有相同 id 但不同时间的讲解员重复了两次。在您看来,是否可以更改答案以获得两个数组,并且对于具有多个日期的老师来说,其中还有另一个数组?(或类似的东西)
因为目前我有:
(3) [{…}, {…}, {…}]
0: {id: "1", name: "name1", surname: "surname1", date: "2020-05-29", start: "09:00:00", end: "10:00:00"}
1: {id: "1", name: "name1", surname: "surname1", date: "2020-05-29", start: "10:00:00", end: "11:00:00"}
2: {id: "2", name: "name2", surname: "surname2", date: "2020-05-29", start: "09:00:00", end: "10:00:00"}
length: 3
__proto__: Array(0)
解决方案
您可以使用以下函数来获得预期的答案:
public function getDocent()
{
$roles = 'Docent';
$arr_return = array();
$query = $this->db->select('Persons.id, Persons.name, Persons.surname, Agenda.date, Agenda.start, Agenda.end')
->from('Persons')
->join('Agenda', 'Persons.id = Agenda.docent_id', 'INNER')
->where('Agenda.free', 'true')
->where('roles', $roles)
->get();
$arr_result = $query->result_array();
foreach($arr_result as $key=>$result)
{
if(!isset($arr_return[$result['id']]))
$arr_return[$result['id']] = array('name'=> $result['name'], 'surname' => $result['surname']);
$arr_return[$result['id']]['docent'][] = array('start'=> $result['start'], 'end'=> $result['end']);
}
//print_r($arr_return);
return $arr_return;
}
输出将如下所示:
Array
(
[1] => Array
(
[name] => Sanjay
[surname] => Surve
[docent] => Array
(
[0] => Array
(
[start] => 09:00
[end] => 10:00
)
[1] => Array
(
[start] => 10:00
[end] => 11:00
)
)
)
[2] => Array
(
[name] => John
[surname] => Doe
[docent] => Array
(
[0] => Array
(
[start] => 09:00
[end] => 10:00
)
)
)
)
注意:您必须根据您的数据库修改字段名称(例如 start 应该是 start_at)。
希望这对你有用。
推荐阅读
- go - 寻找值开头的无效字符“R”
- javascript - Raspberry Pi Fask 服务器:无法使用 AJAX 和损坏的 id 搜索在文件夹中找到图像
- mongodb - 查询以在对象数组中的所有对象都匹配时返回结果
- laravel - 检查密码是否等于用户密码Laravel 7
- puppeteer - 无法单击 puppeteer 中的元素
- c++ - 用两条线拟合曲线的二次算法
- c# - 如何从目录 c# 中运行 python 脚本
- javascript - 使用 javascript 将点击添加到使用 javascript 创建的 img
- python - 如何从文件中读取并将内容放入 Python 中的 json 方法中?
- javascript - 在 3x3 网格中为匹配的行中的 3 个数组构建数组