【问题标题】:Getting data from another table into a blade foreach - Laravel从另一个表中获取数据到刀片 foreach - Laravel
【发布时间】: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-&gt;hosts-&gt;name 替换为var_dump($element) 会得到什么?
  • 您能否确保在您的数据库中您正在使用的connection 的外键不为空?如果connection 没有host_id,则在您使用with 时它不会加载它,这可能会导致您看到的错误。
  • user3158900 - 它不为空,因为当我编写“$element->host_id”时它返回“host_id”的 id。并且具有此 id 的表 hosts 包含值。

标签: php mysql laravel


【解决方案1】:

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

改成return $this-&gt;belongsTo('App\Hosts', 'host_id');

【讨论】:

    【解决方案2】:

    在您的情况下,hosts 属性是数组(集合),因此您需要指定索引或循环遍历它

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 2023-04-02
      • 2022-11-02
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2017-09-22
      • 2017-12-02
      • 1970-01-01
      相关资源
      最近更新 更多