Thinkphp5 关联模型

Posted 狂奔的蜗牛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thinkphp5 关联模型相关的知识,希望对你有一定的参考价值。

必须建立两个模型分类模型(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

 

 

 

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‘)

 

以上是关于Thinkphp5 关联模型的主要内容,如果未能解决你的问题,请参考以下文章

Thinkphp5 关联模型

thinkphp5 模型表关联

ThinkPHP5——模型的一对多关联

关于THINKPHP5模型关联的初步理解

thinkphp利用模型关联来做关联统计

thinkphp5 怎么进行跨库关联查询