首页 > 解决方案 > Laravel Eloquent orderBy() 一对多关系中的父表字段

问题描述

所以我有桌子questions和桌子steps。可以有steps很多。属于一个“步” questionsquestion

我的表中有一个step_id字段,它是我表中字段questions的外键。我的表中还有一个与该字段没有任何关系的字段。它只是一个数字(1-12)。idstepsnumberstepsid

问题表

---------------------------
| 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.* )questionsstepsquestionsstep_idquestionsidquestionsnumber

也许我只是不太了解关系,无法做到这一点。但我不知所措。任何帮助,将不胜感激。

标签: phpmysqllaraveleloquentforeign-keys

解决方案


让我们分解一下这个查询有什么问题(还要注意你在这里做的是一个普通的 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.*']);

推荐阅读