php 在codeigniter4模型中编写函数

gcuhipw9  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(138)

我创建了一个模型,并希望使用模型内部定义的函数获取与模型表相关的详细信息。

<?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'];
    
    }
    
}

可以在模型的类中编写函数吗?我可以使用$this来获取模型类的示例吗

jvlzgdj9

jvlzgdj91#

你可以的。
必须使用第二个版本,因为已经建立了与数据库的连接。

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'];
}

相关问题