2017-12-11 3 views
0

다른 테이블에서 블레이드 foreach로 데이터를 가져 오려고하지만 뷰에 레코드가 표시되지 않습니다.다른 테이블에서 블레이드로 데이터 가져 오기 foreach - Laravel

연결 - 테이블 :

Schema::create('connections', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('host_id')->unsigned(); 
    $table->text('comment'); 
    $table->timestamps(); 
}); 

Schema::table('connections', function (Blueprint $table) { 
    $table->foreign('host_id') 
     ->references('id') 
     ->on('hosts'); 
}); 

호스트 - 테이블 :

Schema::create('hosts', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->text('name'); 
    $table->timestamps(); 
}); 

Connections.php

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Connections extends Model 
{ 
    public function hosts() 
    { 
     return $this->belongsTo('App\Hosts'); 
    } 
} 

Hosts.php

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Hosts extends Model 
{ 
    public function connections() 
    { 
     return $this->hasMany('App\Connections'); 
    } 
} 

ConnectionsController.php

namespace App\Http\Controllers; 

use App\Connections; 
use Illuminate\Http\Request; 

class ConnectionsController extends Controller 
{ 
    public function index() 
    { 
     $connections = Connections::with('hosts')->get(); 
     return view('connections.index', compact('connections')); 
    } 
} 

보기/연결/index.blade.php

<table class="table table-hover"> 
    <tr> 
     <th>Comment</th> 
     <th>Nazwa</th> 
    </tr> 
    @foreach($connections as $element) 
     <tr> 
      <td>{{ $element->comment }}</td> 
      <td>{{ $element->hosts->name }}</td> 
     </tr> 
    @endforeach 
</table> 

"$ 엘리먼트 -> hosts-> 이름이"반환 "코멘트"값하지만 때 추가없이보기 두 번째 줄은 "$ element-> hosts-> name"입니다. "객체가 아닌 속성을 얻으려고하면 오류가 발생합니다 (보기 : /Applications/XAMPP/xamppfiles/htdocs/mdbms/resources/views/connections/index.blade .php) ". 실수가있는 곳이 궁금합니다. 귀하의 경우에는

+0

변경을 당신이'$ element-> hosts-> name'을'var_dump ($ element)'로 대체한다면 당신은 얻을 수 있을까요? – Will

+1

작업중인'connection'에 대한 외래 키가 데이터베이스에 있는지 확인할 수 있습니까? 'connection'에'host_id'가 없다면'with'를 사용할 때로드되지 않습니다. 그러면'error'가 표시 될 수 있습니다. – user3158900

+0

user3158900 - "$ element-> host_id"를 쓸 때 "host_id"의 ​​ID를 반환하므로 null이 아닙니다. 그리고이 id를 가진 테이블 호스트는 값을 포함합니다. – Patryk

답변

0

귀하의 hosts 관계 기능을 통해 인덱스 또는 루프를 지정해야하는 것은 잘못된 것 같다 : return $this->belongsTo('App\Hosts', 'host_id'); 무엇

+0

당신 말이 맞아요. 도와 줘서 고마워. 그것은 작동합니다. – Patryk

0

hosts 속성은 배열 (컬렉션) 그래서 당신이

관련 문제