我有两个表之间的错误,我无法显示数据

时间:2017-09-13 00:10:13

标签: php laravel laravel-5.3 relationship

我有2个表作者和帖子,我有一对多的关系: 这是作者模型

(function() {
    // Get the modal
    var modal = document.getElementById('{{ healthy_alerts.get(dev).get("hostname") }}Modal');

    // ...

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
})();

这是Post model

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

我想显示与该作者相关的所有帖子,我在Controller中使用它

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'));
}

但这没有显示任何内容,我做了什么?

2 个答案:

答案 0 :(得分:1)

而不是$ post只使用Post模块类..比.. $posts = Post::where("author_id", "=", $author->id)->get();

尝试..

答案 1 :(得分:0)

如果您已设置关系,则只需在主表(作者)上运行查询。不需要Second Post查询。 Eloquent将知道其与帖子的关联(关系)。

所以要显示你可以简单地说:

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

希望有帮助...