Laravel 5.4 一对多关系

Laravel 5.4 one to many relationship

我的模型中有两个表: - 组(id、名称、category_id) - 类别(id,名称)

我需要在我的视图中显示一个包含每个组名称及其相应类别的列表。你能告诉我如何填充 Eloquent 方法以及我在视图端需要什么吗?

这是我目前所拥有的,但当然行不通

-- 组控制器

`       public function index()
{
    $groups = Category::find(1);

    return view('groups.groups',compact('groups'));
}

-- 群
public function category() { return $this->belongsTo('App\Category'); }

-- 类别控制器

`       public function groups()
{
    return $this->hasMany('App\Group');
}`

-- 类别

`       public function groups()
{
    return $this->hasMany('App\Group');
}`

-- 查看

@foreach($groups as $group) {{$group->category}} {{$group->category->name}} @endforeach

谢谢!!

一种简单的方法是使用 Eloquent 的预加载: https://laravel.com/docs/4.2/eloquent#querying-relations

Group::with('category')->get() 

例如:

      # Loop through all groups
      foreach(Group::with('category')->get() as $group){
        #get group name
        print $group->name;

        #get all categories related to this group
        $categories =  $group->category;
        foreach ($categories as $category){
            print $category->name;
        }
        print "<br>";
    }

我终于明白了。 在 GroupsController 中添加了这个

´
    $groups = Group::with('category')->get();

    return view('groups.groups',compact('groups'));

´ 并在视图中: @foreach($groups as $group) {{$group->category->name}}

感谢您的帮助

根据我的评论,你想要的是:

模型 + 关系:

群模型

public function category()
{
    return $this->belongsTo(Category::class);
}

类别模型

public function groups()
{
    return $this->hasMany(Group::class);
}

然后在您的组控制器中:

public function index()
{
    // consider using paginate() instead of get()
    // using with('category') to eagerload the category (1 extra query) instead of querying for the category in the views foreach loop.
    $groups = Group::with('category')->get();

    return view('groups.groups',compact('groups'));
}

在您的视图中,您现在可以列出组及其类别:

@foreach ($groups as $group)
    {{-- Assuming group and category have a name and category is always set --}}
    {{ $group->name }} : {{ $group->category->name }}
@endforeach