zoukankan      html  css  js  c++  java
  • thinkphp5.1 模型关联查询输出 整了很久才明白,做个笔记

    1.首先上表和模型

    1.user 用户表
    {
      user_id  //主键
    }
    2.account 账务表
    {
      account_id  //主键
      user_id  //用户外键
    }

    3.User模型
    class
    User extends Model { protected $table = 'yh_user'; protected $pk = 'user_id'; } 4.Account模型 class Account extends Model { protected $table = 'yh_account'; protected $pk = 'account_id'; }

    一、如果需要通过User模型获取到Account模型的数据 第一步先User模型中创建一对多的关联方法 注意是:hasMany()方法
    
    
    class User extends Model
    {
    protected $table = 'yh_user';
    protected $pk = 'user_id';

     //关键操作
    public function account()
    {
    return $this->hasMany('Account','user_id');
    }
     }

    控制器操作
    $data = UserModel::with('account')->select();
    输出结果:
    [2] => array(3) {
        ["user_id"] => int(67)
        ["account"] => array(1) {
          [0] => array(2) {
            ["account_id"] => int(1)
            ["user_id"] => int(67)
          }
        }


    一、如果需要通过Account模型关联获取到User模型的数据 第一步先Account模型中创建反关联方法 注意是:belongsTo()方法

    class Account extends Model
    {
    protected $table = 'yh_account';
    protected $pk = 'account_id';

    //关键操作
    public function User()
    {
    return $this->belongsTo('User','user_id');
    }
    }

    控制器操作:
    $data = AccountModel::with('User')->select();
    dump($data);

    输出结果:
    array(1) {
      [0] => array(8) {
        ["account_id"] => int(1)
        ["user_id"] => int(67)
        ["user"] => array(11) {
          ["user_id"] => int(67)
        }
      }
    }
  • 相关阅读:
    Android简易抽屉效果
    apk 下载并自动安装
    python2.7_1.3_获取远程设备的IP地址
    python2.7_1.2_打印设备名和IPv4地址
    python2.7_1.14_编写一个简单的回显客户端/服务器应用
    python2.7_1.13_编写一个SNTP客户端
    C语言程序转换为Python语言
    5分钟弄懂Docker!
    让正则表达式变简单(PythonVerbalExpressions)
    python sqlalchemy-migrate 使用方法
  • 原文地址:https://www.cnblogs.com/tiaoma888/p/thinkphp.html
Copyright © 2011-2022 走看看