Laravel 5.4一对多关系

时间:2017-06-06 09:55:45

标签: laravel-5.4 laravel-eloquent

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

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

这是我到目前为止所做的,但当然不起作用

- GroupController

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

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

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

- CategoryController

`       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

谢谢!

3 个答案:

答案 0 :(得分:0)

一种简单的方法是使用Eloquent的Eager Loading: 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>";
    }

答案 1 :(得分:0)

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

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

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

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

感谢您的帮助

答案 2 :(得分:0)

跟进我的评论,你想要的是以下内容:

模特+关系:

群组模型

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