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

 

posted @ 2019-11-17 20:58  渴死的鱼0521  阅读(2346)  评论(0编辑  收藏  举报