hasOne (本模型有一个外部模型,其外键
belongsTo(本模型中键属于外部模型的外键
一对一、一对多、多对多
关于软删除,默认关联是保留,不用额外操作,但是join的话需要把delete_time 的null判断加入。
一对一 hasOne (本模型有一个外部模型,其外键与本模型主键关联)belongsTo(本模型中键属于外部模型的外键,与外部模型的主键关联)
在user模型中需要关联模型的其中加入一个profile方法。其中Profile为已经存在的模型文件
public function profile(){
return $this->hasOne(Profile::class);
}
#缩写了外键 profile中的user_id
$this->hasOne(Profile::class,"user_id","id");
表示User模型的id主键与profile模型中的外键user_id关联
public function profile()
{
return $this->hasOne(Profile::class);
}
下面是belongs 在profile模型 本模型中有个user_id 属于外部模型user的主键id关联
public function user()
{
// 定义反向关联
return $this->belongsTo(User::class, 'user_id');
}
一对多 hasMany(本模型有多个外部模型) belongsTo (多个属于一个 所以还是用belongsTo)
return $this->hasMany(Book::class)->order('pub_time');
//上面是省略参数,
//尾部的order可以实现排序
return $this->hasMany(Book::class, 'user_id', 'id')->order('pub_time');
目前的User模型本省的主键,与book模型的user_id实现多个关联
namespace app\model;
use think\Model;
class User extends Model
{
public function book()
{
return $this->hasMany(Book::class)->order('pub_time');
}
}
多对多 belongsToMany 有4个参数 【引入模型参数】【 本模型参数】
至少3张表
- user_role用户权限表(中间表不需要建立模型)
public function roles(){
return $this->belongsToMany(Role::class, 'user_role', 'role_id', 'user_id');
}
public function users(){
return $this->belongsToMany(User::class, 'user_role', 'user_id', 'role_id');
}
方法 :本模型为user的情况下
1.为外表模型
2.关联表(不用模型)
3.关联表中,外表模型的外键 role_id
4.关联表中 ,本表(当前模型)的关联的外键user_id
5.id 本模型的主键 user 可以省略
6.id 关联模型的主键 role 可以省略
》》》with 关联查询《《《 关联模型再关联
$m=$b->with([“a.c”])->select()
$b模型中a是关联,a与c关联 ,
访问$m 循环 $a 循环 $c 前端使用多个volist去取出数据
多对多 中间表 pivot: $m[‘pivot’][‘xxx’];//中间表数据
ORDER 排序
一对多
return $this->hasMany(LeaseModel::class,"lease_id",'id')->order("po_id");
//按照关联表(LeaseModel) 的po_id排序
多对多
public function propertyone(){
return $this->belongsToMany(PropertyOneModel::class,'lease','po_id','lease_id')->order("propertyone.id");
}
//propertyone的id排序
->order("id")
//中间表 lease的id 排序