2017-09-03 1 views
0

두 테이블이 있고 그 테이블에서 데이터를 검색하여 테이블에 전달하고 싶습니다.Laravel에서 여러 테이블에서 데이터를 검색하는 방법 5.4

[ADRESS]

class Adress extends Model 
{  
    public function KontoKorrent() 
    { 
     return $this->hasOne(KontoKorrent::class, 'Adresse'); 
    } 
} 

[KontoKorrent이 같은

class KontoKorrent extends Model 
{ 
    public function Adresse() 
    { 
     return $this->belongsTo(Adress::class,'Adresse'); 
    } 
} 

내 컨트롤러보기 :

나는 하나 개의 관계에 대한 하나 2 개 모델을 만든이를 위해

class AdressesController extends Controller 
{ 
    public function index() 
    { 
    $adresses = Adress::with('KontoKorrent')->paginate(2); 
     return view('welcome', compact('adresses')); 

    } 
} 

내가 사용할 때 tinker App \ Adress :: 모든 adresskontokorrent과 관련이있다. 이것은 작동 중입니다. 내보기에서

App\Adress {#698 
     Adresse: "3030", 
     Anrede: "Company", 
     Name1: "A Company Name", 
     LieferStrasse: "Dummystreet", 
     KontoKorrent: App\KontoKorrent {#704 
      Location: "1", 
      Adresse: "3030", 
      Kto: "S0043722", 

: 관계는 나에게 오류를 보여주는

<ul> 
    @foreach($adresses as $adress) 
    <li>{{ $adress->Name1 }}</li> //this is working 
    <li>{{ $adress->KontoKorrent->Kto }}</li> //this is NOT working 
    @endforeach 
</ul> 

{{ $adresses->links() }} 

: 내가 잘못

Trying to get property of non-object

을하고있어 무엇?

답변

0

당신이 점점 오류 :

Trying to get property of non-object

일부 Adress 모델에 관련이 다음 KontoKorrent, 당신의 $adress->KontoKorrent 반환 null이없는, 그리고 널 (null)이, 객체지지 않습니다의 이유가 메시지. PHP> = 7.0

{{ $adress->KontoKorrent ? $adress->KontoKorrent : 'the else content' }} 

또는, 당신은 할 수 있습니다

<ul> 
    @foreach($adresses as $adress) 
    <li>{{ $adress->Name1 }}</li> //this is working 
    <li> 
     @if($adress->KontoKorrent) 
      {{ $adress->KontoKorrent->Kto }} 
     @else 
      <!-- Put something here if you want, otherwise remove the @else --> 
     @endif 
    </li> //this is NOT working 
    @endforeach 
</ul> 

이이 단축 될 수 adress이 관계가있는 경우

를 해결하려면, 당신은 확인하기 위해 if을 수행해야합니다 null coalesce 연산자를 사용하십시오.

{{ $adress->KontoKorrent ?? 'the else content' }} 
+1

사실 일부 null 항목이 있습니다. 고마워 이것이 내 문제를 해결했다. –

관련 문제