search
HomePHP FrameworkThinkPHPDetailed explanation of the difference between has_one and belongs_to under ThinkPHP5

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. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools