【发布时间】:2018-05-25 11:52:39
【问题描述】:
我正在尝试将另一个表中的数据获取到刀片 foreach 中,但是我的查询未在视图中显示任何记录。
连接 - 表:
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>
没有“$element->hosts->name”的视图返回“comment”值,但是当我添加带有“$element->hosts->name”的第二行时,我收到一个错误“尝试获取非属性-对象(查看:/Applications/XAMPP/xamppfiles/htdocs/mdbms/resources/views/connections/index.blade.php)”。不知道哪里错了。
【问题讨论】:
-
如果将
$element->hosts->name替换为var_dump($element)会得到什么? -
您能否确保在您的数据库中您正在使用的
connection的外键不为空?如果connection没有host_id,则在您使用with时它不会加载它,这可能会导致您看到的错误。 -
user3158900 - 它不为空,因为当我编写“$element->host_id”时它返回“host_id”的 id。并且具有此 id 的表 hosts 包含值。