我正在尝试在 Codeigniter 中进行查询,以允许用户检索他们过去提交到我的数据库的记录。
这是我的模式:
我无法弄清楚我需要为我的一些表做什么
例如 1:M 或 M:M
- 1 procedure 有 1 个或多个 procedure_event
- procedure_event 可能会或可能不会使用资源
- 1 个流程有 1 名或多名员工
我想我需要为此使用 Select、Joins,我已经完成了其中的一些,但是对于多对多关系和链接表,我不知道如何做。
这是我到目前为止在代码方面得到的,但它没有返回任何行,所以我认为这是错误的:
public function view_record($record_id)
{
//The criteria used for WHERE is a variable with array of procedure_id = record_id that is passed to function
$criteria = array
(
'procedure_id' => $record_id
);
//this selects the columns from procedure table for use in joins
$this->db->select('procedure.procedure_id, procedure.patient_id, procedure.department_id, procedure.name_id , procedure.dosage_id');
//this is the table I want to use the columns from
$this->db->from ('procedure');
//this joins the patient row that matches its ID to the patient ID in the procedure table
$this->db->join('patient', 'patient.patient_id = procedure.patient_id', 'inner');
//this joins the department row that matches its ID to the patient ID in the procedure table
$this->db->join('department', 'department.department_id = procedure.department_id', 'inner');
//this joins the procedure_name row that matches its ID to the patient ID in the procedure table
$this->db->join('procedure_name', 'procedure_name.procedure_name_id = procedure.name_id', 'inner');
//this joins the dosage row that matches its ID to the patient ID in the procedure table
$this->db->join('dosage', 'dosage.dosage_id = procedure.dosage_id', 'inner');
//this selects the row in procedure table that matches the record number
$this->db->where('procedure_id', $record_id);
/*
Code for other tables:
I need help with
procedure_event, staff, resources, hr
*/
//this part I think is wrong
$result = $this->db->get();
//
if ($result->num_rows >0)
{
echo "There is Data!";
}
else
{
echo "No Data!";
}
我收到一条消息说“没有记录”但是我的表等中有数据:
所以到目前为止我的查询一定是错误的。
感谢您的宝贵时间!
最佳答案
首先,我个人认为用纯文本编写如此复杂的查询比使用 Active Records 更容易。
您所有的连接都使用 inner;那就是所有的行都需要在另一个表中找到一个伙伴。如果其中任何一个不存在,您将获得 0 行。考虑使用 LEFT JOIN,如前所述。
目前所有这些表都包含数据吗?
是否绝对需要在这些表中的每个表中都有一个合作伙伴行,或者您是否指望缺少行的情况?
关于php - 帮助选择,使用 CodeIgniter 连接多个表 - MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6899259/