您的位置 首页 php

详解ThinkPHP5下has_one和belongs_to的区别

下面由thinkphp框架教程栏目给大家介绍ThinkPHP5下has_one和belongs_to的区别,希望对需要的朋友有所帮助!

ThinkPHP5下has_one和belongs_to的区别

在查阅了相关Tp5开发文档和相关博客后,总结出关于belongsTo和hasOne的区别,主要是看你是在哪一个model(模型)中编写这个关联关系,父关联对象就是在父关联model(本文是在Products的model类)下编写的关联模型。下面是两种关联的使用时机。


has_one(或has_many):外键在子关联对象中

例子:

//父关联对象表Products{ id product_name}//子关联对象表Image{ image_id img_name product_id    //foreign key}
在TP5中的写法为:
//hasOne方法的参数包括://hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');//默认的join类型为INNER//写在Products的model类中public function Img(){  $this->hasOne('Image','product_id','id');}

belongs_to:外键在你父联对象中

//父关联对象表:Product{ product_id img_id    //foreignkey product_name}//子关联对象表Image{ id       img_name}
在TP5中的写法为:
//belongsTo方法的参数包括://belongsTo(‘关联模型名’,‘外键名’,‘关联表主键名’,[‘模型别名定义’],‘join类型’);//默认的join类型为INNER//写在Products的model类中public function Img(){$this->belongsTo('Image','img_id','id');}

文章来源:智云一二三科技

文章标题:详解ThinkPHP5下has_one和belongs_to的区别

文章地址:https://www.zhihuclub.com/26072.shtml

关于作者: 智云科技

热门文章

网站地图