2017-09-13 72 views
0

我有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 

但這不顯示任何東西,我做了什麼?

回答

0

如果您已經建立關係,則只需要在主表(作者)上運行查詢。第二個帖子不需要查詢。雄辯會知道它與帖子的關係。

因此,爲了顯示你可以簡單地說:

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

希望幫助...

+0

這不行! '''802a64dd0c6b2877a7d37b8dab7df504d4e5ed3b.php中的ErrorException錯誤36行: 嘗試獲取非對象的屬性'''我試圖顯示有關作者的信息,它的工作良好,但是當我得到所有帖子,這不起作用! –

1

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

嘗試。 。

+0

比你,它的工作 –

相關問題