039.CI4框架CodeIgniter,封装Model模型绑定数据库的封装

01、ModelBase.php代码如下:

复制代码
<?php

namespace App\Models;

use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use CodeIgniter\Validation\ValidationInterface;

class ModelBase extends Model
{
    var $Db;

    function __construct(ConnectionInterface $db = null,
                         ValidationInterface $validation = null)
    {
        parent::__construct($db, $validation);
        //创建数据库连接
        $this->Db = \Config\Database::connect();
    }

    //--------------------------------------------------------------------
    public function find($id = false)
    {
        if ($id === false) {
            return $this->findAll();
        }
        return $this->where(['id' => $id])->first();
    }

    public function date_insert($data)
    {
        return $this->insert($data);
    }

    public function date_update($data, $id)
    {
        return $this->update($id, $data);
    }

    public function date_delete($id)
    {
        return $this->delete($id);
    }

}
复制代码

02、Model_usertoken.php代码如下:

复制代码
<?php

namespace App\Models;

class Model_usertoken extends ModelBase
{
    protected $table = 'user_token';
    protected $primaryKey = 'id';
    protected $allowedFields = ['username', 'token', 'exp_time'];

    public function __construct()
    {
        parent::__construct();
    }

    public function date_query($date)
    {
        $id = $date['id'];
        //sql语句
        $sql = 'SELECT * FROM `user` WHERE `ID` IN ? ';
        //带参数条件查询
        $rst = $this->db->query($sql,
            [$id]
        );
        echo $this->db->getLastQuery();
        return $rst->getResultArray();
    }

}
复制代码

03、调用如下:

复制代码
<?php

namespace App\Controllers\Auth;

use App\Controllers\BaseController;

class Login extends baseController
{
    protected $userModelToken;


    function __construct()
    {
        $this->Jwt = new Tx_jwt;
        $this->userModelToken = model('App\Models\Model_usertoken');
    }

    //http://localhost/phmci4/public/index.php/auth/login/test001
    public function test001()
    {
        $param = array(
            'id' => [1],
        );
        $data = $this->userModelToken->date_query($param);
        ShowMessage($data);
    }

}
复制代码

04、结构如下:

 05、浏览器效果如下:

 

posted @   像一棵海草海草海草  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2019-08-31 2019年年度计划与九月计划
2019-08-31 十九、库房_从报废库报废航材
2019-08-31 十八、库房_从可用库报废一个周转件(未完结)
点击右上角即可分享
微信分享提示