在本次实战中,需要建立如下的数据库,数据库名为student,下表为tp_user:
下面需要注意:1)username和email设置为唯一索引,防止重复;2) 配置表前缀tp_,位置为config/database.php。
模块搭建
可以使用命令快捷新建资源控制器:User.php:
php think make:controller User
在controller下会生成该类,并自动构建一些方法:
在model下创建User.php,示例代码如下:
<?php
namespace app\model;
use think\Model;
class User extends Model{
}
需要设置资源路由
//用户模块资源路由
Route::resource('user', 'User');
在controller下的User类中的index方法中,实现获取数据并将数据传入模板的功能(这里的paginate是使用了分页的功能,每页只展示5条数据):
public function index()
{
return View::fetch('index',[
'list' => ModelUser::order('id', 'asc')->paginate(5),
]);
}
在模板部分view\user\index(User资源控制器在使用View类下的fetch方法时,会自己去寻找view下面和自己同名的文件夹,fetch的第一个参数即为定位到的文件名)中,采用{volist}遍历显示数据:
{volist name="list" id="obj"}
<tr>
<td class="text-center">{$obj.id}</td>
<td>{$obj.username}</td>
<td class="text-center">{$obj.gender}</td>
<td class="text-center">{$obj.email}</td>
<td>{$obj.status}</td>
<td class="text-center">{$obj.create_time}</td>
<td class="text-center">
<button class="btn btn-danger btn-sm">删除</button>
<button class="btn btn-warning btn-sm">修改</button>
</td>
</tr>
{/volist}