一对一、一对多、多对多
关于软删除,默认关联是保留,不用额外操作,但是join的话需要把delete_time 的null判断加入。
一对一 hasOne (本模型有一个外部模型)belongsTo(本模型中键属于外部模型)
在user模型中需要关联模型的其中加入一个profile方法。其中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权限表 模型
- user_role用户权限表(中间表不需要建立模型)
public function roles(){
return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id');
}
public function users(){
return $this->belongsToMany(User::class, 'user_role', 'role_id', 'user_id');
}