我正在尝试将其他表中的数据放入刀刃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->主机->名称”的视图返回“注释”值,但是当我在第二行中添加“ $ element->主机->名称”时,出现错误“试图获取非对象的属性(查看:/Applications/XAMPP/xamppfiles/htdocs/mdbms/resources/views/connections/index.blade.php)”。我想知道哪里有错误。
最佳答案
您的hosts
关系函数似乎不正确:
将其更改为return $this->belongsTo('App\Hosts', 'host_id');
关于php - 从另一张表获取数据到 Blade foreach-Laravel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47761716/