php - Laravel Eloquent orderBy() 一对多关系中的父表字段
问题描述
所以我有桌子questions
和桌子steps
。可以有steps
很多。属于一个“步” questions
。question
我的表中有一个step_id
字段,它是我表中字段questions
的外键。我的表中还有一个与该字段没有任何关系的字段。它只是一个数字(1-12)。id
steps
number
steps
id
问题表
---------------------------
| id | step_id | question |
---------------------------
步骤表
-----------------------------
| id | number | description |
-----------------------------
我的关系工作正常,因为我可以从questions
表格中创建、更新和删除问题。但是,我正在索引页面上工作,我想获取所有问题并按表中的number
字段对它们进行排序steps
。
我做了一些研究,我从 Laracasts 中找到了一些代码,但它不起作用。网站上没有提供太多信息。我是否需要依赖项才能获得此功能,或者在 laravel 中是否有本地方式来执行此操作。
$questions = Question::join('steps', 'questions.step_id', '=', 'questions.id')
->orderBy('questions.number', 'asc')
->get(['questions.*']);
我收到以下错误:
SQLSTATE [42S22]:未找到列:1054 'order 子句'中的未知列 'questions.number'(SQL:从. = . order by .asc上的内部连接中选择
questions
.* )questions
steps
questions
step_id
questions
id
questions
number
也许我只是不太了解关系,无法做到这一点。但我不知所措。任何帮助,将不胜感激。
解决方案
让我们分解一下这个查询有什么问题(还要注意你在这里做的是一个普通的 SQL 连接,而不是使用 Eloquent 关系——这对于这种情况是正确的):
// You are comparing the `step_id` on `questions` to the `id` on `questions`
// Which doesn't make sense, you should compare it to the `id` on `steps` table
$questions = Question::join('steps', 'questions.step_id', '=', 'questions.id')
// You're trying to order by a column on `steps` table, but
// you're explicitily looking for it on `questions` table
->orderBy('questions.number', 'asc') // <-- you get the SQL error because of this
->get(['questions.*']);
现在让我们解决这些问题:
$questions = Question::join('steps', 'questions.step_id', '=', 'steps.id')
->orderBy('steps.number', 'asc')
->get(['questions.*']);
推荐阅读
- docker - 如何将自定义 DNS 区域文件内容添加到运行在 127.0.0.11 的 docker 嵌入式 DNS 服务器?
- php - 热修复“警告:mysqli_stmt::bind_param():类型定义字符串中的元素数与绑定变量数不匹配”?
- r - 使用 read.xlsx 时未使用的参数
- database - 如何在vba中填充文本框
- kotlin - 未找到/丢失 AndroidX 可穿戴包
- java - 活动在某些设备中无法正常工作
- google-cloud-ml - 在 Google Cloud Platform 上启用和使用推荐 AI
- c# - 如何仅重置 Mock 4.12 中的模拟设置?
- excel - 如果多个范围内的值为空,则为 Msgbox
- ionic-framework - 在 Android 上创建 CouchbaseLite DB 的问题 - CORS 问题