首页 > 解决方案 > Laravel Eloquent relation not retrieving data from related table

问题描述

Iv got a simple "publications" table and "Languages" table as seen below. All I want to do is output "available languages" associated with the publication. iv tried relationships this way and that and cnt get it right

Publications Table

Languages Table

Controller:

public function index()
{

    $publications = Publication::all();

    $languages = Language::all();

    return view('admin/publications/index', compact('publications', 'languages'));

}

Publication Model relationship:

public function languages(){

    return $this->hasMany('App\Language');

}

Publications Page

Please help!

标签: phplaraveleloquent

解决方案


Use with to include relations:

public function index()
{
    $publications = Publication::with('languages')->get();

    return view('admin/publications/index', compact('publications'));
}

This allows you to then access the related models like:

foreach ($publication->languages as $language) {
    echo $language->myAttribute;
}

推荐阅读