【问题标题】:Laravel Eloquent orderBy() parent table field in a One to Many RelationshipLaravel Eloquent orderBy() 一对多关系中的父表字段
【发布时间】:2018-05-21 00:00:49
【问题描述】:

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

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

问题表

---------------------------
| id | step_id | question |
---------------------------

步骤表

-----------------------------
| id | number | description |
-----------------------------

我的关系工作正常,因为我可以从 questions 表中创建、更新和删除问题。但是,我正在处理索引页面,我想抓取所有问题并按steps 表中的number 字段对它们进行排序。

我做了一些研究,并从 Laracasts 中找到了一些代码,但它不起作用。网站上没有提供太多信息。我是否需要依赖才能获得此功能,或者在 laravel 中是否有本地方式来执行此操作。

$questions = Question::join('steps', 'questions.step_id', '=', 'questions.id')
->orderBy('questions.number', 'asc')
->get(['questions.*']);

我收到以下错误:

SQLSTATE[42S22]:未找到列:1054 未知列 'order 子句' 中的 'questions.number' (SQL: select questions.* from questions 内部连接 ​​steps questions.step_id = questions.id 按questions.number asc 订购)

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

【问题讨论】:

    标签: php mysql laravel eloquent foreign-keys


    【解决方案1】:

    让我们来分析一下这个查询有什么问题(还请注意,您在这里执行的是普通 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.*']);
    

    【讨论】:

    • 好答案。很好的解释。
    • +devk @devk 感谢您的回答,现在有没有办法对这个结果进行分页?我在上一个问题中忘记问了。
    • @J.Robinson 是的,只需这样做:-&gt;select('questions.*')-&gt;paginate() 而不是 -&gt;get(..)。
    • 你先生是一个绝对的老板!非常感谢你! :P 这有很大帮助! :P 让它 100% 按我想要的方式工作!
    猜你喜欢
    • 2021-10-04
    • 2019-05-14
    • 1970-01-01
    • 2013-02-09
    • 2017-04-20
    • 1970-01-01
    • 2020-07-12
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多