別のテーブルからブレード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) "私はどこに間違いがあるのだろうか。
へ
変更、それを何あなたが '$ element-> hosts-> name'を' var_dump($ element) 'に置き換えればあなたは得られますか? – Will
あなたのデータベースで、作業している 'connection'の外部キーがヌルでないことを確認できますか? 'connection'に' host_id'がない場合、あなたが見ているエラーを引き起こす可能性のある 'with'を使うと、' connection'にロードされません。 – user3158900
user3158900 - "$ element-> host_id"と書くと "host_id"のIDを返すので、nullではありません。そして、このidのテーブルホストには値が入っています。 – Patryk