我有两个表之间的误差,我不能显示数据

问题描述:

我有2名表,作者和文章和我有关系一对多: 这是作者模型我有两个表之间的误差,我不能显示数据

public function author(){ 
    return $this->hasMany('App\Post'); 
} 

,这是Post模型

public function author(){ 
    return $this->belongsTo('App\Author','author_id'); 
} 

我我想表明与此相关的作者的所有讯息,我在控制器

public function author(Author $author, Post $post,$name) 
{ 
    $authors = Author::where('name', $name) 
     ->firstOrFail(); 
    $posts = $post->where("author_id", "=", $author->id)->get(); 
    return view('author', compact('authors','posts')); 
} 

使用和这在刀片上

@foreach($posts as $post) {{ $post->title }} @endforeach 

但这不显示任何东西,我做了什么?

如果您已经建立关系,则只需要在主表(作者)上运行查询。第二个帖子不需要查询。雄辩会知道它与帖子的关系。

因此,为了显示你可以简单地说:

@foreach ($authors as $author) 
    {{ $author->posts->title }} 
@endforeach 

希望帮助...

+0

这不行! '''802a64dd0c6b2877a7d37b8dab7df504d4e5ed3b.php中的ErrorException错误36行: 尝试获取非对象的属性'''我试图显示有关作者的信息,它的工作良好,但是当我得到所有帖子,这不起作用! –

,而不是$后只使用邮政模块class..like .. $posts = Post::where("author_id", "=", $author->id)->get();

尝试。 。

+0

比你,它的工作 –