itsource

Laravel 관련 모델이 있는지 확인

mycopycode 2023. 1. 15. 17:21
반응형

Laravel 관련 모델이 있는지 확인

관련된 모델이 있는 웅변형 모델이 있습니다.

public function option() {
    return $this->hasOne('RepairOption', 'repair_item_id');
}

public function setOptionArrayAttribute($values)
{
    $this->option->update($values);
}

모델을 작성할 때 반드시 관련된 모델이 있는 것은 아닙니다.업데이트할 때 옵션을 추가할 수도 있고 추가하지 않을 수도 있습니다.

따라서 관련 모델이 존재하는지 확인하고 업데이트 또는 생성해야 합니다.

$model = RepairItem::find($id);
if (Input::has('option')) {
    if (<related_model_exists>) {
        $option = new RepairOption(Input::get('option'));
        $option->repairItem()->associate($model);
        $option->save();
        $model->fill(Input::except('option');
    } else {
       $model->update(Input::all());
    }
};

서 ★★★★★<related_model_exists>찾고 있는 코드입니다.

php 7.2+에서는 사용할 수 없습니다.count모든 관계에 대해 만능적인 방법은 없습니다.@yyy하다

$model->relation()->exists()

모든 관계 유형(php 7.2 이전):

if (count($model->relation))
{
  // exists
}

속성이 반환되므로 됩니다.Model ★★★★★★★★★★★★★★★★★」Collection 모두 「 」를 실장하고 .ArrayAccess.

그래서 다음과 같이 됩니다.

일일: : hasOnebelongsTomorphTomorphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

다관계: 다관계: hasManybelongsToManymorphManymorphToManymorphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

Relation 객체는 알 수 없는 메서드 호출을 관련 객체만 선택하도록 설정된 Alutive Query Builder로 전달합니다.해당 Builder는 알 수 없는 메서드 호출을 기본 쿼리 Builder로 전달합니다.

즉, 또는 메서드를 관계 오브젝트에서 직접 사용할 수 있습니다.

$model->relation()->exists(); // bool: true if there is at least one row
$model->relation()->count(); // int: number of related rows

괄호는 해 주세요.relation->relation()는 함수 객체 입니다.->relationLaravel lar lar larter terter terter terter lar lar lar lar lar lar lar lar lar lar 。

「 」의 count 오브젝트의 괄호를 는, 「아, 아, 아, 아, 아, 아, 아, 아)」를 실행하는 것보다 훨씬 빠릅니다.$model->relation->count() ★★★★★★★★★★★★★★★★★」count($model->relation)(관계가 이미 고속으로 로드된 경우는 제외) 관련 오브젝트의 모든 데이터를 데이터베이스에서 꺼내는 것이 아니라 카운트 쿼리를 실행하기 때문에 카운트만 할 수 있습니다. 「」를 사용해 주세요.exists이치노

다.exists() ★★★★★★★★★★★★★★★★★」count()했던 모든 에 대해 가가도 i i i i i i i i i i i i i i i work work work work work work, work work work work work?belongsTo,hasOne,hasMany , , , , 입니다.belongsToMany.

사용하는 것을 선호합니다.exists★★★★

RepairItem::find($id)->option()->exists()

관련 모형의 존재 여부를 확인합니다.라라벨 5.2에서는 정상적으로 동작하고 있습니다.

Php 7.1 이후로는 모든 유형의 관계에서 허용되는 답변이 작동하지 않습니다.

은 '언변', '', '언변은 '언변'을 한다.Collection ,a ,aModel ★★★★★★★★★★★★★★★★★」NullPhp 7.1에서는 count(null)error

따라서 관계가 존재하는지 확인하려면 다음을 사용할 수 있습니다.

, " " 등'hasOne그리고.belongsTo

if(!is_null($model->relation)) {
   ....
}

관계가 여러 개인 경우:예:hasMany그리고.belongsToMany

if ($model->relation->isNotEmpty()) {
   ....
}

모델 개체에서 relationLoaded 메서드를 사용할 수 있습니다.이게 내 베이컨을 구했으니 다른 사람에게 도움이 되길 바라.내가 라라카스트에 대해 같은 질문을 했을 때 는 이 제안을 받았다.

Hemerson Varela가 이미 Php 7.1에서 말했듯이count(null)던지다error그리고.hasOne돌아온다null행이 없는 경우.이왕이면hasOne내가 사용하는 관계empty확인 방법:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {
   $option = $model->option;

   if(empty($option)){
      $option = $model->option()->create();
   }

   $option->someAttribute = temp;
   $option->save();
};

하지만 이건 불필요합니다.이 관계가 존재하는지 여부를 확인할 필요는 없습니다.update또는create호출합니다. updateOrCreate 메서드를 사용하면 됩니다.이는 위와 같습니다.

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {  
   $model->option()
         ->updateOrCreate(['repair_item_id' => $model->id],
                          ['option' => $temp]);
}

Larabel 5에서 이것이 변경되었는지 확실하지 않지만, 다음과 같은 방법으로 답변할 수 있습니다.count($data->$relation)관련 속성에 액세스한 바로 그 동작으로 로딩이 되었기 때문에 작동하지 않았습니다.

결국, 직설적인 것은isset($data->$relation)날 위해 묘기를 부렸지

단일 관계에 사용합니다.hasOne,belongsTo그리고.morphs

if($model->relation){ 
 ....
}

조건이 null일 경우 이는 false가 되기 때문입니다.

여러 관계의 경우:hasMany,belongsToMany그리고.morphs

if ($model->relation->isNotEmpty()) {
   ....
}

카운트($x) 함수의 잘못된 사용으로 인해 PHP 버전을 7.2+로 업데이트했을 때 코드를 완전히 수정해야 했습니다.다양한 시나리오에서 수백 가지 사용법이 존재하며 모든 것을 충족시키는 규칙이 없기 때문에 이는 매우 고통스럽고 매우 무서운 일입니다.

모든 것을 재검토하기 위해 지켰던 규칙, 예:

$x = Auth : : user ( ) - > posts - > find ( 6 ) ; ( - > find ( )를 사용하여 사용자가 Post ID = 6 인지를 확인합니다)

[FAILS] if(count($x)) { return 'Found'; } 
[GOOD] if($x) { return 'Found'; }

$x = Auth : : user() - > profile - > departments ; (프로파일에 몇 개의 부서가 있는 경우는, 복수의 부서가 있는 것을 확인해 주세요)

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

$x = Auth : : user ( ) - > profile - > get ( ) ; ( - > get ( )를 사용한 후 사용자에게 프로파일이 있는지 확인)

[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }

이것이 도움이 되기를 바라며, 질문이 있은 지 5년이 지났지만, 이 스택 오버플로우 게시물은 나에게 많은 도움이 되었습니다!

모델 클래스를 사용하고 웅변적 ORM을 사용하는 경우 새 메서드를 만들고 bool 데이터를 반환합니다.맘에 들다

public function hasPosts(): bool
{
    return $this->posts()->exists();
}

언급URL : https://stackoverflow.com/questions/23910553/laravel-check-if-related-model-exists

반응형