0

모델 사이에 사용자 지정 Eloquent 관계가있는 2 개의 테이블이 있습니다. 관계는 Kredittkort.leverandor_id가 사용자 지정 관계 후 관계가있는 Eloquent 모델을 가져 오는 방법

class Bankleverandor extends Model { 
protected $primaryKey = 'fpid'; 
protected $guarded = []; 
public function kredittkort() { 
    return $this->hasMany("App\Kredittkort", 'leverandor_id', 'fpid'); 
}} 

class Kredittkort extends Model { 
protected $guarded = []; 
protected $primaryKey = 'fpid'; 
public function bankleverandor() { 
    return $this->belongsTo("App\Bankleverandor", "leverandor_id", 'fpid'); 
}} 

관계가 잘 작동을 Bankleverandor.fpid

를 참조하여 정직하고 있습니다. 예를 들어

Kredittkort::find(258053)->bankleverandor; 
Bankleverandor::find(441)->kredittkort; 

이 예상되는 결과는 Eloquent ORM에 관계가 올바르게 정의되어 있음을 나타냅니다. 그러나 절 "로"를 사용하여 관계를 호출하면 나는 내가 위의 경우에서 관계를 검색 할 수있는 방법을 이해하려는

Kredittkort::with(["\App\Bankleverandor" => function($q) {return $q->select("fpid,orgnr"); }]); 

을 다음과 같이 관계를 검색하기 위해 노력하고 예외를

RelationNotFoundException in RelationNotFoundException.php line 20:Call to undefined relationship [\App\Bankleverandor] on model [App\Kredittkort]. 

가 발생합니다. 또 다른 추천 방법이 있다면, 나뿐만 아니라

답변

1

난 당신이 찾고있는 무슨 생각을 알고 싶어요입니다 : Constraining Eager Loads

+0

감사합니다. 클래스의 네임 스페이스를 사용하여 관계를 잘못로드했습니다. – Prakhar

0

: 여기

Kredittkort::with(['bankleverandor' => function ($query) { 
    $query->select('fpid','orgnr'); 
}])->get(); 

이 문서에 대한 링크입니다 비슷한 문제에 직면 해있는 사람들에게. 나는 관련 클래스의 정규화 된 이름을 사용하여 관계를 잘못로드하고있었습니다. 대신에 나는 belongsTo 관계를 정의한 메소드 이름 (bankleverandor)을 사용해야한다.

잘못된 사용 :

Kredittkort::with(["\App\Bankleverandor" => function($q) { return $q->select("fpid,orgnr"); }]);

올바른 사용법 : 답변

Kredittkort::with(['bankleverandor' => function ($query) { $query->select('fpid','orgnr'); }])->get();