可以';t在Laravel中加载带有评论的帖子


Can't load Post with Comment in Laravel

以下是关系式:

注释模型

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方法。

您可能应该更改

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

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

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

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

如果您希望无论何时提取Comment,都会同时提取与其相关的Post,只需在Comment Model 中使用以下属性

protected $with = ['post'];

它应该急于加载相关的Post

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

同时,我建议在这里读一点关于with()load()之间的区别