라라벨에서 BelongsToHasOne과 HasOne의 차이점은 무엇입니까?
누가 나에게 주요 차이점이 무엇인지 말해줄 수 있습니까?
BelongsTo and 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의 역입니다.
belongSo 메서드를 사용하여 hasOne 관계의 역수를 정의할 수 있습니다.간단한 예를 들어 보겠습니다.
User
그리고.Phone
모형
사용자에서 전화기로 하나의 관계를 제공합니다.
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
이 관계를 사용하여 사용자 모델을 사용하여 전화기 모델 데이터를 얻을 수 있습니다.
그러나 HasOne을 사용하는 Inverse 공정에서는 불가능합니다.전화기 모델을 사용한 액세스 사용자 모델과 같습니다.
전화를 사용하여 사용자 모델에 액세스하려면 전화 모델에 BelongsTo를 추가해야 합니다.
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
자세한 내용은 이 링크를 참조하십시오.
일대일 관계:사용자는 하나의 프로파일을 가질 수 있습니다.물론 그 반대도 마찬가지입니다.사용자를 프로파일링합니다.사용자는 둘 이상의 프로파일을 가질 수 없으며 프로파일은 여러 사용자에게 속할 수 없습니다.
두 테이블 사이에 일대일 관계를 만들고 싶다면 먼저 "has One" 관계를 만들고, 반대로 테이블 관계를 만들고 싶다면 "belong to" 관계를 만듭니다.IT는 HasOne과 Belongs의 단순한 차이입니다. 만약 당신이 이 One To Many에 대해 알고 싶다면 (Inverse)
게시물의 모든 주석에 액세스할 수 있으므로 주석이 상위 게시물에 액세스할 수 있도록 관계를 정의합니다.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');
}
}
언급URL : https://stackoverflow.com/questions/37582848/what-is-the-difference-between-belongsto-and-hasone-in-laravel
'programing' 카테고리의 다른 글
연결을 사용하여 업데이트 후속 처리 (0) | 2023.08.29 |
---|---|
조건부 춘두 생성 (0) | 2023.08.29 |
MariaDB가 충돌하는 이유를 찾는 방법은 무엇입니까? (0) | 2023.08.29 |
일반 오류 해결 방법: 2006 MySQL 서버가 사라졌습니다. (0) | 2023.08.29 |
제거/무시 방법: 터치 장치에서 css 스타일을 호버합니다. (0) | 2023.08.29 |