路由規(guī)則和分組支持綁定模型數(shù)據(jù),例如:
Route::rule('hello/:id','index/hello/index','GET',[
'ext' => 'html',
'bind_model' => [
'user' => '\app\index\model\User',
],
]);
會(huì)自動(dòng)給當(dāng)前路由綁定 id為 當(dāng)前路由變量值的User模型數(shù)據(jù)。就是自動(dòng)讀取到cms_user
(我設(shè)置了表前綴‘cms_’,設(shè)置是‘think_user’)表的對(duì)應(yīng)id數(shù)據(jù)。下面實(shí)例:(這個(gè)環(huán)節(jié)需要鏈接數(shù)據(jù)庫操作,下面我會(huì)把數(shù)據(jù)表簡(jiǎn)單展示)
- 在application/index/controller新建一個(gè)
Hello.php
,如下:
<?php
namespace app\index\controller;
use think\Controller;
class Hello extends Controller{
public function index(){
// dd($this->request->user);//自己封裝的打印數(shù)據(jù)的方法,自己打印下就知道$this->request->user就是自動(dòng)讀取的數(shù)據(jù)
$user = $this->request->user;
return $user;
}
}
- 在application/index/model下面新建一個(gè)
User.php
模型,里面只需要把框架搭好就行,不需要任何方法(有也無所謂),如下:
<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
}
- 我的數(shù)據(jù)表
- 現(xiàn)在執(zhí)行訪問網(wǎng)址:
http://tp5.demo/hello/12.html
,就能看到頁面輸出如下json數(shù)據(jù):
{"id":12,"user_name":"車易拍","datetime":1499387617,"thumb":"\/Public\/Uploads\/2017-07-07\/595ef597ae7d4.jpg","is_top":1,"cate_pid":15}
如果訪問的是http://tp5.demo/hello/1.html
這個(gè)id=1不在數(shù)據(jù)表中,就會(huì)報(bào)模型數(shù)據(jù)不存在:app\index\model\User
錯(cuò)誤,因?yàn)闆]有查到數(shù)據(jù)。
- 也可以增加限制條件(其他地方不變,只變路由),如:
Route::rule('hello/:id/:user_name','index/hello/index','GET',[
'ext' => 'html',
'bind_model' => [
'user' => ['\app\index\model\User','id&user_name'],
],
]);
ps:這塊的user_name要和你的數(shù)據(jù)空中字段對(duì)應(yīng),否則會(huì)報(bào)相應(yīng)錯(cuò)誤
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_name1' in 'where clause'
現(xiàn)在訪問tp5.demo/hello/12/車易拍.html
則也會(huì)顯示數(shù)據(jù)空中id=12的內(nèi)容。
{"id":12,"user_name":"車易拍","datetime":1499387617,"thumb":"\/Public\/Uploads\/2017-07-07\/595ef597ae7d4.jpg","is_top":1,"cate_pid":15}