无法在Laravel中加载带评论的帖子

时间:2016-07-28 10:15:38

标签: php laravel post load comments

Theese是关系:

评论模型

class Comment extends Model
{

    /**
     *
     * The comment belongs to the post
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function post()
    {
        return $this->belongsTo('App\Post', 'post_id')->with('Post');
    }

}

发布模型

class Post extends Model
{


    /**
     *
     * a post has many comments
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

然后尝试检查传递的内容:

$comment = Comment::findOrFail($id);

        return Response()->json($comment);

    }

只有评论的东西是没有关系的,我不明白,不应该急于在评论中加载帖子吗?

如果我从模型中删除->with('Post');并使用

$comment = Comment::findOrFail($id)->load('Post');

Post会被加载,但无论如何都应该使用Model方法。

3 个答案:

答案 0 :(得分:0)

你应该改变

$comment = Comment::findOrFail($id)->load('Post');

$comment = Comment::with('Post')->findOrFail($id);

答案 1 :(得分:0)

如果你返回一个JSON对象,你必须Comment::with('Post')...否则它不会急于加载查询(https://laravel.com/docs/5.1/eloquent-relationships#eager-loading

但是,如果您将模型对象传递到视图return view('welcome', compact('comment'))的位置,则可以调用$comment->post,这是您的Post对象,延迟加载。

答案 2 :(得分:0)

如果您希望每当提取Comment时,都需要同时提取Post,只需使用Comment模型中的以下属性

protected $with = ['post'];

它应该急切加载相关的Post

是的,您需要从关系中删除->with('post')部分。它不会做你期望它做的事情。

与此同时,我建议您仔细阅读with()load() here

之间的区别