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,效果如下: