在Laravel 5中递归关系中如何获取包含回复?

3

我有一个名为 replies 的表,包含论坛 Laravel 应用程序中主题的所有回复。

**replies Table**
---------------
    reply_id
    content
    topic_id
    reply_by
    embed_reply
    created_at
    updated_at

回复可以包含另一个回复。为此,有一个名为embed_reply的列,它保存了所包含回复的reply_id

现在我想在获取父回复时同时获取所包含回复的详细信息。

为此,我在回复模型中添加了以下方法:

public function included_reply ()
        {
            return $this->with('replies', function ($query) {
                $query->where('reply_id',$this->embed_reply);
            });
        }

如果要获取特定主题的回复,可以这样写:

$topic = Topic::whereTopicId($id)
                ->with([
                    'replies' => function ($query) {
                        $query->orderBy('created_at', 'desc');
                    }
                    , 'replies.included_reply'
                ])
                ->first();

下面的所有内容都返回以下错误:
BadMethodCallException in Builder.php line 2071:
Call to undefined method Illuminate\Database\Query\Builder::replies()

我不知道如何做到这一点。 有什么解决方法?


如果您在控制器中执行该查询,则必须包含您的模型,即使用 ModelName; - Ajit Kumar Singh
我使用了所有必需的模型。 - Ahmad Badpey
1个回答

0

我在以下时间得到了答案:

laracasts.com/discuss

这是我必须添加的关系:

public function embed()
{
    return $this->belongsTo(Reply::class, 'embed_reply');
}

还有这个用于获取那个:

$reply = Reply::find($reply_id);
$embed = $reply->embed;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接