Home > PHP Framework > ThinkPHP > body text

Detailed explanation of the difference between has_one and belongs_to under ThinkPHP5

藏色散人
Release: 2020-11-24 15:47:56
forward
2724 people have browsed it

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
}
Copy after login
is written in TP5 as:
//hasOne方法的参数包括:
//hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
//默认的join类型为INNER
//写在Products的model类中
public function Img(){
  $this->hasOne('Image','product_id','id');
}
Copy after login

belongs_to: The foreign key is in your parent object

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

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!