037.CI4框架CodeIgniter,使用Model模型绑定数据库表

01、我们创建一个数据库,如下:

复制代码
CREATE TABLE `user`  (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `userpassword` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `details` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `admin` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `group` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(3) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
复制代码

 02、TestUser.php代码如下:

复制代码
<?php

namespace App\Controllers\Test;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

//访问地址:http://localhost/phmci4/public/index.php/test/testuser
class TestUser extends BaseController
{
    use ResponseTrait;

    protected $userModel;

    function __construct()
    {
        $this->userModel = model('App\Models\Model_user');
    }

    //http://localhost/phmci4/public/index.php/test/testuser/index
    function index()
    {
        echo "哈哈!";
    }

    //http://localhost/phmci4/public/index.php/test/testuser/testgetuser
    function testgetuser()
    {
        $data = $this->userModel->getUser();
        return $this->respondCreated($data);
    }

    //http://localhost/phmci4/public/index.php/test/testuser/testinsert
    function testinsert()
    {
        $user = array(
            'username' => 'tianpan',
            'userpassword' => 'guest',
            //如果没有在$allowedFields中,那么不会被增加和修改
            'details' => 'good'
        );
        $data = $this->userModel->insertUser($user);
        return $this->respondCreated($data);
    }
}
复制代码

03、Model_user.php代码如下:

复制代码
<?php

namespace App\Models;

use CodeIgniter\Model;

class Model_user extends Model
{
    protected $table = 'user';
    protected $primaryKey = 'id';
    protected $allowedFields = ['username', 'userpassword'];

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

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

    public function updateUser($data, $id)
    {
        return $this->update($id, $data);
    }
}
复制代码

04、代码结构如下:

 05、访问http://localhost/phmci4/public/index.php/test/testuser/testgetuser,效果如下:

 

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