只是想问我如何在CodeIgniter 4上使用INNER JOIN函数?我正试图将下面的SQL语句转换为CodeIgniter 4,但由于我只是这个领域的新手,我发现很难。
SELECT l.l_id, u.fname, u.mname, u.lname, u.dept, u.user_type, u.u_grdsec, e.e_name, l.date_added, DATE(l.date_added), date_format(l.date_added, '%H:%i') as 'time'
FROM logs l INNER JOIN users u ON l.u_id = u.u_id
INNER JOIN establishment e ON l.e_id = e.e_id
WHERE DATE(l.date_added) = '$rep_date'
GROUP BY
date_format(l.date_added, '%H:%i'), l.u_id
ORDER BY l.date_added ASC";
经过研究,我发现了这个方法。但是,我不知道如何在那里放置WHERE, GROUP BY和ORDER BY子句。
$builder = $this->db->table("logs as l");
$builder->select('l.l_id, u.fname, u.mname, u.lname, u.dept, u.user_type, u.u_grdsec, e.e_name, l.date_added, DATE(l.date_added), date_format(l.date_added, "%H:%i") as "time"');
$builder->join('users as u', 'l.u_id = u.u_id');
$builder->join('establishment as e', 'l.e_id = e.e_id');
$data = $builder->get()->getResult();
另一件让我困惑的事是我不知道我应该把它放在哪里。我不知道我应该把它放在Controller
还是Model
文件上。
public function getLogs(){
helper(['form']);
$model = new LogsMod();
$rep_est = $this->request->getPost('rep_est');
$rep_date = $this->request->getPost('rep_date');
$data['logs_data'] = $model->where('DATE(l.date_added)', $rep_date)->groupBy(date_format(l.date_added, '%H:%i'), l.u_id)->orderBy('l.date_added', 'ASC')->findAll();
return view()->to('LogsReport', $data);
}
这里是我的模型上的代码。
public function getLogs(){
$builder = $this->db->table("logs as l");
$builder->select('l.l_id, u.fname, u.mname, u.lname, u.dept, u.user_type, u.u_grdsec, e.e_name, l.date_added, DATE(l.date_added), date_format(l.date_added, "%H:%i") as "time"');
$builder->join('users as u', 'l.u_id = u.u_id');
$builder->join('establishment as e', 'l.e_id = e.e_id');
$data = $builder->get()->getResult();
}
然而,我不认为这两者有联系。
CodeIgniter 4模型本身就是构建器。可以使用类变量
指定db表protected $table = '<your table>';
类扩展CodeIgniterModel。当在函数中构建查询时,您可以简单地使用$this来引用构建器。所以你的函数可以像这样:
public function getLogs(){
$this->select('l.l_id, u.fname, u.mname, u.lname, u.dept, u.user_type, u.u_grdsec, e.e_name, l.date_added, DATE(l.date_added), date_format(l.date_added, "%H:%i") as "time"');
$this->join('users as u', 'l.u_id = u.u_id');
$this->join('establishment as e', 'l.e_id = e.e_id');
$this->where(...);
$this->orderBy(...);
return $this->findAll();
}
where()方法接受键值数组或变量/字符串对:
$this->where(['key1' => 'value1','key2' => 'value2' ]);
// or
$this->where('key1', 'value1');
$this->where('key2', 'value2');
其中key1和key2是您的数据库表字段。
注意,在你的控制器中,你应该使用model()函数实例化你的模型对象:
$model = model(LogsMod::class);