Laravel通过另一个关系检索关系数据
我有三张桌子 问题表格:Laravel通过另一个关系检索关系数据,laravel,eloquent,relationship,Laravel,Eloquent,Relationship,我有三张桌子 问题表格: id title description id answerbody question_id id answer_id 答案表格: id title description id answerbody question_id id answer_id 喜欢表格: id title description id answerbody question_id id answer_id 我想检索单个问题的详细信息,包括所有答案和答案数量及其各自的喜好(仅限于
id
title
description
id
answerbody
question_id
id
answer_id
答案表格:
id
title
description
id
answerbody
question_id
id
answer_id
喜欢表格:
id
title
description
id
answerbody
question_id
id
answer_id
我想检索单个问题的详细信息,包括所有答案和答案数量及其各自的喜好(仅限于喜欢数量)
我试过这个
public function show($id)
{
return question::with(['answers','answers.likes'])->withCount(['answers'])->where('id',$id)-
>get();
}
如何使用count返回喜欢的内容?每个问题都有许多答案。因此,在问题模型中添加以下代码:
public function answer()
{
return $this->hasMany(Answer::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
每个答案都有许多相似之处。因此,在回答模型中添加以下代码:
public function answer()
{
return $this->hasMany(Answer::class);
}
public function likes()
{
return $this->hasMany(Like::class);
}
现在,您必须在问题模型中定义一个mutator“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();
通过这种方式,您还可以根据他们的喜好计数对答案进行排序您在项目中定义了关系吗?是的,我定义了关系。一切正常。我只需要将喜好计数。这似乎回答了您的问题。使用@AnuratChapanond我尝试了这个返回问题::with(['answers')->with count(['answers','likes')->where('id',$id)->get();它抛出了一个错误SQLSTATE[42S22]:未找到列:1054未知列“likes.question_id”@RaffianMoin如果有效,请给出您的预期结果请接受此答案或花点时间进行检查