다른 테이블에서 블레이드 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) ". 실수가있는 곳이 궁금합니다. 귀하의 경우에는
에
변경을 당신이'$ element-> hosts-> name'을'var_dump ($ element)'로 대체한다면 당신은 얻을 수 있을까요? – Will
작업중인'connection'에 대한 외래 키가 데이터베이스에 있는지 확인할 수 있습니까? 'connection'에'host_id'가 없다면'with'를 사용할 때로드되지 않습니다. 그러면'error'가 표시 될 수 있습니다. – user3158900
user3158900 - "$ element-> host_id"를 쓸 때 "host_id"의 ID를 반환하므로 null이 아닙니다. 그리고이 id를 가진 테이블 호스트는 값을 포함합니다. – Patryk