首页 > 其他 > 详细

总结7.15 tp5关联

时间:2020-07-24 17:55:39      阅读:79      评论:0      收藏:0      [点我收藏+]

一对一关联,A表中一条数据对应B表中一条数据

class User extends Model{

    public function profile()

    {

        return $this->hasOne(‘Profile‘)->field(‘id,name,email‘);

    }}

//hasOne(‘关联模型名‘,‘外键名‘,‘主键名‘,[‘模型别名定义‘],‘join类型‘);

$user = User::get(1);

echo $user->profile->email;

//关联查找,输出Profile关联模型的email属性

$user = User::get(1);

$user->profile()->save([‘email‘ => ‘thinkphp‘]);

//关联新增,如果还没有关联数据 则进行新增

$user = User::get(1);

$user->profile->email = ‘thinkphp‘;

$user->profile->save();

//关联更新

一对多关联,A表中一条数据对应B表多条数据

class Article extends Model {

    public function comments()

    {

        return $this->hasMany(‘Comment‘);

    }}

//hasMany(‘关联模型名‘,‘外键名‘,‘主键名‘,[‘模型别名定义‘]);

多对多关联,A表中一条数据对应B表多条数据并且B表中一条数据对应A表中多条数据

class User extends Model {

    public function roles()

    {

        return $this->belongsToMany(‘Role‘);

    }}

//belongsToMany(‘关联模型名‘,‘中间表名‘,‘外键名‘,‘当前模型关联键名‘,[‘模型别名定义‘]);

总结7.15 tp5关联

原文:https://www.cnblogs.com/HighKK/p/13372790.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!