![](/img/trans.png)
[英]Phalcon: What is the difference between hasOne and belongsTo in 1-1 relationship?
[英]What is the difference between BelongsTo And HasOne in Laravel
誰能告訴我兩者之間的主要區別是什么
在雄辯的屬於關聯和HasOne關系。
主要區別在於關系的哪一側持有關系的外鍵。 調用$this->belongsTo()
的模型是one-to-one
和many-to-one
關系中的擁有模型,並擁有擁有模型的鍵。
一對一關系示例:
class User extends Model {
public function car() {
// user has at maximum one car,
// so $user->car will return a single model
return $this->hasOne('Car');
}
}
class Car extends Model {
public function owner() {
// cars table has owner_id field that stores id of related user model
return $this->belongsTo('User');
}
}
一對多關系示例:
class User extends Model {
public function phoneNumbers() {
// user can have multiple phone numbers,
// so $user->phoneNumbers will return a collection of models
return $this->hasMany('PhoneNumber');
}
}
class PhoneNumber extends Model {
public function owner() {
// phone_numbers table has owner_id field that stores id of related user model
return $this->belongsTo('User');
}
}
BelongsTo是HasOne的逆函數。
我們可以使用belongsTo方法定義hasOne關系的逆函數。 以
User
和Phone
模型為例。
我給從用戶到電話hasOne關系。
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
使用此關系,我可以使用用戶模型獲取電話模型數據。
但是使用HasOne進行逆過程是不可能的。 類似於使用電話模型的訪問用戶模型。
如果要使用Phone訪問用戶模型,則必須在Phone模型中添加BelongsTo 。
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
您可以參考此鏈接以獲取更多詳細信息。
一對一關系:作為用戶,您可以擁有一個( hasOne )配置文件。 當然,逆也適用。 為用戶配置文件( belongsTo )。 一個用戶不能有多個配置文件,並且一個配置文件不能屬於多個用戶。
如果要在兩個表之間建立一對一關系,那么首先必須建立“ hasOne”關系,如果要使表反向,則要建立““屬於” ......這是HasOne和如果您想了解一對多(反向),則屬於該關系
現在我們可以訪問帖子的所有評論,讓我們定義一個關系,以允許評論訪問其父帖子。 要定義hasMany關系的逆關系,請在子模型上定義一個關系函數,該函數調用belongsTo
方法:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
在這里你可以看到一個很好的例子,看看有什么區別雄辯 屬於關聯和HasOne之間的關系。
雄辯的關系備忘單,Mahmoud Zalt https://link.medium.com/9lj9BAG8lR
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.