Home >PHP Framework >ThinkPHP >Detailed explanation of the difference between has_one and belongs_to under ThinkPHP5

Detailed explanation of the difference between has_one and belongs_to under ThinkPHP5

藏色散人
藏色散人forward
2020-11-24 15:47:463012browse

The following is the thinkphp framework tutorial column to introduce to you the difference between has_one and belongs_to under ThinkPHP5. I hope it will be helpful to friends in need!

The difference between has_one and belongs_to under ThinkPHP5

After consulting the relevant Tp5 development documents and related blogs, I summarized the difference between belongsTo and hasOne, mainly depending on which model you are in ( This association is written in the model), and the parent association object is the association model written under the parent association model (this article is in the model class of Products). The following are the times when the two associations are used.


has_one (or has_many): the foreign key is in the child association object

Example:

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

belongs_to: The foreign key is in your parent object

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

The above is the detailed content of Detailed explanation of the difference between has_one and belongs_to under ThinkPHP5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete