// 定义模型类
class UserModel extends Model
{
    protected $table = 'user'; // 表名

    // 查询所有用户
    public function getAllUsers()
    {
        return $this->select();
    }

    // 根据用户ID查询用户
    public function getUserById($id)
    {
        return $this->where('id', $id)->find();
    }

    // 新增用户
    public function addUser($data)
    {
        return $this->save($data);
    }

    // 更新用户信息
    public function updateUser($id, $data)
    {
        return $this->where('id', $id)->update($data);
    }

    // 删除用户
    public function deleteUser($id)
    {
        return $this->where('id', $id)->delete();
    }
}

// 在控制器中使用模型
class UserController extends Controller
{
    // 获取所有用户
    public function index()
    {
        $userModel = new UserModel();
        $users = $userModel->getAllUsers();

        // 其他操作...

        $this->assign('users', $users);
        return $this->fetch('index');
    }

    // 新增用户
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $userModel = new UserModel();
            $result = $userModel->addUser($data);

            // 其他操作...

            if ($result) {
                $this->success('添加成功', 'index');
            } else {
                $this->error('添加失败');
            }
        } else {
            return $this->fetch('add');
        }
    }

    // 编辑用户
    public function edit($id)
    {
        $userModel = new UserModel();
        $user = $userModel->getUserById($id);

        // 其他操作...

        $this->assign('user', $user);
        return $this->fetch('edit');
    }

    // 更新用户信息
    public function update()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $data = $this->request->post();
            $userModel = new UserModel();
            $result = $userModel->updateUser($id, $data);

            // 其他操作...

            if ($result) {
                $this->success('更新成功', 'index');
            } else {
                $this->error('更新失败');
            }
        }
    }

    // 删除用户
    public function delete($id)
    {
        $userModel = new UserModel();
        $result = $userModel->deleteUser($id);

        // 其他操作...

        if ($result) {
            $this->success('删除成功', 'index');
        } else {
            $this->error('删除失败');
        }
    }
}
以上代码演示了如何在ThinkPHP框架中使用数据模型进行数据库操作。通过定义模型类,我们可以方便地执行查询、新增、更新和删除操作。在控制器中,我们可以实例化模型类并调用相应的方法来实现业务逻辑。使用数据模型可以提高开发效率,并使代码更加规范和易于维护。