Laravel 通过另一个关系检索关系数据

Laravel retrieve relationship data via another relationship

我有三个table

问题 table:

id
title
description

回答 table:

id
answerbody
question_id

table:

id
answer_id

我想检索单个问题的详细信息,包括所有答案和 answer_count 以及他们各自的喜好(仅 like_count)

我试过了

public function show($id)
{
    return question::with(['answers','answers.likes'])->withCount(['answers'])->where('id',$id)- 
    >get();
}

我如何 return 点赞数?

每个问题都有很多答案。所以在问题模型中添加以下代码:

public function answer()
    {
        return $this->hasMany(Answer::class);
    }

每个回答都有很多赞。所以在 Answer 模型中添加以下代码:

public function likes()
    {
        return $this->hasMany(Like::class);
    }

现在您必须在问题模型中定义一个修改器“getDataAttribute”,如下所示:

public function getDataAttribute()
    {
        return [
            'question' => $this,
            'answers' => $this->answers()->get(),
            'answer_count' => $this->answers()->get()->count(),
            'likes' => $this->answers()->likes()->get(),
        ];
    }

最后,在您需要问题信息的任何地方,您只需调用:

$question->data

检索问题、喜欢和问题计数。

如果您需要一个问题的所有答案以及他们的点赞数,您可以在 with() 子句中调用闭包并将他们的相关点赞数加载为

Question::with(['answers'=> function ($query) {
                $query->withCount('likes')
                      ->orderBy('likes_count', 'desc');
        }])
        ->withCount(['answers'])
        ->where('id',$id)
        ->get();

这样您还可以根据喜欢的数量对答案进行排序