必須建立兩個模型分類模型(attr)、文章模型(article)
attr模型
<?php namespace app\common\model; use think\Model; class Attr extends Model{ }
article模型
1 <?php 2 namespace app\common\model; 3 use think\Model; 4 5 class Article extends Model{ 6 7 }
hasOne(一對一關聯)
關聯查詢
<?php namespace app\common\model; use think\Model; class Attr extends Model{ // 關聯文章模型 public function article() { //return $this->hasOne('article','pid','id','','INNER'); return $this->hasOne('article','pid'); } public function s(){ $id = 19; $attr = $this->get($id); // 查詢單條 //$res = $attr->article()->find(); // 查詢多條 $r = $attr->article; // 打印出來數據(article+attr內容) $rr = $attr->article->parent->data; // 打印attr內容 $rrr = $attr->article->data; // 打印出來article內容; $r = $this->toCollection($rrr); return $r; } }
查詢出來的是article內容(只有一條數據)。比如:一個用戶,只有一份身份信息
關聯保存
hasMany(一對多關聯)
1 <?php 2 namespace app\common\model; 3 use think\Model; 4 5 class Attr extends Model{ 6 // 關聯文章模型 7 public function article() 8 { 9 return $this->hasMany('article','pid','id'); 10 //return $this->hasOne('article','pid'); 11 } 12 // 可用 13 public function s(){ 14 $id = 9; 15 $attr = $this->get($id); 16 // 查詢單條 17 //$res = $attr->article()->find(); 18 // 查詢多條 19 $res = $attr->article()->select(); 20 return $res; 21 22 } 23 24 }
控制器調用
1 <?php 2 namespace app\index\controller; 3 use think\Controller; 4 use think\Model; 5 class Index extends Controller 6 { 7 protected $model; 8 public function _initialize() 9 { 10 parent::_initialize(); // TODO: Change the autogenerated stub 11 $this->model = model('attr'); 12 } 13 14 public function index(){ 15 $d = $this->model->s(); 16 print_r($d); 17 } 18 19 20 21 }
輸出結果:只有article 內容(沒有attr內容)。hasMany關聯相當於Model('article')。一個用戶可以看多本數