tp5关联
关联:
一对一关联:A表中一条数据对应B表一条数据
一对多关联:A表中一条数据对应B表多条数据
多对多关联:A表中一条数据对应B表多条数据并且B表中一条数据对应A表中多条数据
一对一关联
定义一对一关联,例如,一个用户都有一个个人资料。
hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
classUserextendsModel{
publicfunctionprofile()
{
return$this->hasOne('Profile');
}}
可以支持为关联模型定义需要查询的字段
classUserextendsModel{
publicfunctionprofile()
{
return$this->hasOne('Profile')->field('id,name,email');
}}
关联查找
$user=User::get(1);
// 输出Profile关联模型的email属性
echo $user->profile->
关联新增
$user=User::get(1);// 如果还没有关联数据 则进行新增
$user->profile()->save(['email'=>'thinkphp']);
关联更新
$user=User::get(1);
$user->profile->'thinkphp';
$user->profile->save();// 或者
$user->profile->save(['email'=>'thinkphp']);
定义相对的关联
我们可以在Profile模型中定义一个相对的关联关系
belongsTo('关联模型名','外键名','关联表主键名',['模型别名定义'],'join类型');
classProfileextendsModel{
publicfunctionuser()
{
return$this->belongsTo('User');
}}
一对多关联
一对多关联的情况也比较常见,使用hasMany方法定义,
hasMany('关联模型名','外键名','主键名',['模型 $model = new like();
别名定义']);
classArticleextendsModel{
publicfunctioncomments()
{
return$this->hasMany('Comment');
}}
多对多关联
我们的用户和角色就是一种多对多的关系
b
belongsToMany('a关联模型名','c中间表名','aid外键名','bid当前模型关联键名',['模型别名定义']);
classUserextendsModel{
publicfunctionroles()
{
return$this->belongsToMany('Role');
}}
纯菜

浙公网安备 33010602011771号