将另一个表中的数据转换为刀片foreach - Laravel

时间:2017-12-11 21:28:51

标签: php mysql laravel

我正在尝试将另一个表中的数据转换为刀片foreach但是我的查询没有在视图中显示任何记录。

connections - table:

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');
});

hosts - table:

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-&gt; hosts-&gt; name”的视图会返回“comment”值但是当我用“$ element-&gt; hosts-&gt; name”添加第二行时,我收到错误“试图获取非对象的属性(查看:/Applications/XAMPP/xamppfiles/htdocs/mdbms/resources/views/connections/index.blade.php)“。我想知道哪里有错误。

2 个答案:

答案 0 :(得分:0)

在你的情况下hosts属性是数组(集合),所以你需要指定索引或循环它

答案 1 :(得分:0)

您的hosts关系函数似乎不正确:

将其更改为return $this->belongsTo('App\Hosts', 'host_id');