sql - Advanced Laravel Query
问题描述
Here is my Schema:
The User
model is normal.
Question
- team_id
- question_body
Answer
- user_id
- question_id
- order
- is_private
A user can have a primary
answer for a question which is essentially the answer that has the lowest order
and is public.
I need to get the primary answer of a question for each user except the authenticated user. I have tried multiple ways but can't seem to figure it out. Here is what I have so far on the Question
model:
public function topAnswerForEachMember()
{
return $this->load(['answers' => function($query) {
return $query->public()
->where('user_id', '!=', Auth::user()->getKey());
}]);
}
This returns all public answers to the question not owned by the auth user. Now from here I need to get the one with the lowest order from each user. I have tried groupBy
but am getting aggregate errors for that. I'm guessing this is going to require a sub query of sorts but I am unfamiliar with those. If anyone has an idea it would be much appreciated. Thanks!
解决方案
如果我了解您要做什么,我认为如果您从相反的角度进行操作,这可能是最简单的。我会使用用户模型并从那里提取你的答案。这是一个更简单的查询。
我不确切知道您的关系是什么,或者该public()
方法的作用是什么,但是这样的事情应该接近您的意图:
$users = User::whereHas('answers', function($query) use($question_id){
$query->where('question_id', $question_id)
->orderBy('order', 'asc')->first();
})
->where('id', "!=", Auth::user()->id)
->get();
从这里开始,user
该集合中的每一个都应该有一个单一的、最低的排序answer
到question
您正在查看的内容。如果您还希望获得多个答案,您也可以替换limit()
。first()
推荐阅读
- accessibility - 试图理解咏叹调和可访问性
- vue.js - vue 路由器未定义
- c# - 第二个查询未能更新,因为第一个查询仍在插入过程中
- python-3.x - 使用 selenium 和 python 时发生 ElementNotInteractableException
- javascript - 单击时如何使文本区域扩展?
- angular - 如何扩展 CdkVirtualScrollViewport 角度材质组件?
- jquery - django-smart-selects 无法与 jquery.formset.js django 一起正常工作
- php - 使用 PHP 将 HTML 表单值写入文件
- javascript - 如何将函数从类父组件传递给子功能组件
- html - 为什么我的电子邮件签名文本颜色未在浏览器中显示?