调试记得把 Debug 模式打开,这样你才能定位到大部分错误,过滤掉无关紧要的基础错误,比如语法错误,配置错误。
定义一个数据模型很简单,只需要放到应用的 model 目录下,并且继承 think\Model。
<?php
namespace app\model;
use think\Model;
class Discuzx extends Model
{
}
使用模型
<?php
namespace app\controller;
use app\BaseController;
use app\model\Discuzx;
class Index extends BaseController
{
public function index()
{
// 查找具体 uid 数据
$member = Discuzx::where('uid', 1)->find();
}
}
可以看出, 操作数据特别简便,前提是你需要在 config\database.php 配置好默认的数据库相关信息。假设需要动态切换数据库、表名、表前缀、主键ID名等等,可以在模型属性中配置。
<?php
namespace app\model;
use think\Model;
class Discuzx extends Model
{
// 手动指定表明,前提已经配置表前缀
protected $name = 'ucenter_members';
// 主键ID名
protected $pk = 'uid';
// 完整表名
// protected $table = 'pre_ucenter_members';
// 需要切换数据库可以配,不指定则连接默认数据库
// protected $connection = 'discuzx';
}
详细配置请查阅官方手册。
为什么查询不到数据?
首先你要确认配置无误,没有任何报错后,再检查你的模型是否存在构造函数 __construct ,否则将无法获取到数据。
如果需要做模型的初始化操作,请使用官方规定的方式处理。
<?php
namespace app\model;
use think\Model;
class Discuzx extends Model
{
// 手动指定表明,前提已经配置表前缀
protected $name = 'ucenter_members';
// 主键ID名
protected $pk = 'uid';
// 完整表名
// protected $table = 'pre_ucenter_members';
// 需要切换数据库可以配,不指定则连接默认数据库
// protected $connection = 'discuzx';
// 模型初始化
protected static function init()
{
//TODO:初始化内容
}
}