2017-12-11 13 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->名" を返す "コメント" の値が、ときに私が追加なし2番目の行は "$ element-> hosts-> name"です。エラーが発生しました "非オブジェクトのプロパティを取得しようとしています(View:/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'を使うと、' connection'にロードされません。 – 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プロパティが配列(コレクション)であるので、あなたはそれを介して、インデックスまたはループを指定する必要が

関連する問題