详解ThinkPHP5下has_one和belongs_to的区别

详解ThinkPHP5下has_one和belongs_to的区别,第1张

详解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://outofmemory.cn/web/702768.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存