我的应用程序在两个模型之间建立了以下关系。
Post.php
public function category()
{
return $this->belongsTo('App\Category', 'category_id')->withDefault();
}
Category.php
public function post()
{
return $this->hasMany('App\Post', 'category_id');
}
我想以以下格式获取数据:
类别标题1
类别标题2
类别标题
控制器
$posts = Post::all();
$categories = $posts->pluck('category')->unique();
查看/刀片
@foreach($categories as $category)
{{ $category->name }}
@foreach($category as $item)
{{ $item->post->name }}
@endforeach
@endforeach
不起作用。我期待任何建议。
答案 0 :(得分:0)
更改关系。在关系中添加外键。您不必选择类别和帖子中的其他变量。如果正确分配了关系,关系将获得所有数据。
public function category()
{
return $this->belongsTo('App\Category', 'category_id','category_id');
}
public function post()
{
return $this->hasMany('App\Post', 'category_id','category_id');
}
$categories = Category::all();
可见
@foreach($categories as $category)
{{$category->name}}
@foreach($category->post as $post)
{{$post->title}}
@endforeach
@endforeach
答案 1 :(得分:0)
我认为最好将manyToMany
方法名(posts
而不是post
使用复数形式,但是在当前情况下,此代码应该可以工作:
@foreach($categories as $category)
{{$category->name}}
@foreach($category->post as $item)
{{$item->title}}
@endforeach
@endforeach`