zoukankan      html  css  js  c++  java
  • Thinkphp5 关联模型

    必须建立两个模型分类模型(attr)、文章模型(article) 

    attr模型

    <?php
    namespace appcommonmodel;
    use thinkModel;
    
    class Attr extends Model{
      
      
    }

    article模型

    1 <?php
    2 namespace appcommonmodel;
    3 use thinkModel;
    4 
    5 class Article extends Model{
    6 
    7 }

    hasOne(一对一关联)

    关联查询

    <?php
    namespace appcommonmodel;
    use thinkModel;
    
    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 appcommonmodel;
     3 use thinkModel;
     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 appindexcontroller;
     3 use thinkController;
     4 use thinkModel;
     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')。一个用户可以看多本数

  • 相关阅读:
    一些个人看到觉得还不错的资料,现在先把记得的保存下来,以后碰到会继续更新
    鼠标 mouseover和mouseout事件
    phpqrcode 生成二维码
    django url路径与模板中样式相对路径的问题
    js parseInt和map函数
    WebService 布置简单的计算器
    java ++的使用
    java 运算符
    Java的概念
    public 有跟没有的区别
  • 原文地址:https://www.cnblogs.com/wesky/p/9083020.html
Copyright © 2011-2022 走看看