[英]Writing functions inside codeigniter4 models
我创建了一个 model 并希望使用 model 中定义的函数获取与模型表相关的详细信息。我有以下 model class 的代码片段。
<?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
class DepartmentModel extends Model
{
protected $table = 'tbl_department';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $allowedFields = ['vchr_departmentName','int_divisionID', 'vchr_address'];
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
public function getDeptID($userid)
{
$db = \Config\Database::connect();
$builder=$db->table('tbl_department')
$builder->select('tbl_department.id');
$builder->join('tbl_employee','tbl_department.id=tbl_employee.int_departmentID');
$builder->where('tbl_employee.int_userID',$userid);
$res=$builder->get()->getRowArray();
return $res['id'];
}
public function getDeptName($int_departmentID)
{
$result = $this->where('id',$int_departmentID)->find();
return $result['vchr_departmentName'];
}
}
可以在模型的 class 中编写函数吗?我可以使用 $this 来获取 model 类的实例吗
是的你可以。
您必须使用第二个版本,因为已经建立了与数据库的连接。
public function getDeptID($userid)
{
$res = $this->select('tbl_department.id')
->join('tbl_employee','tbl_department.id=tbl_employee.int_departmentID')
->where('tbl_employee.int_userID',$userid)
->get()
->getRowArray();
return $res['id'];
}
public function getDeptName($int_departmentID)
{
$result = $this->where('id',$int_departmentID)->find();
return $result['vchr_departmentName'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.