【问题标题】:How Products is order by relation in Laravel?Laravel 中如何按关系订购产品?
【发布时间】:2021-02-10 03:40:43
【问题描述】:

如何根据与 table2 的连接对 table1 中的产品进行排序,即通过 table2 中的 example_relation 对 table1 中的产品进行排序?

表1

| id | product |
|----|---------|
| 1  | pro1    |
| 2  | pro2    |
| 3  | pro3    |
| 4  | pro4    |
| 5  | pro5    |

表2

| id | example_relation | product_id |
|----|------------------|------------| 
| 1  | 700              | 1          |
| 2  | 800              | 2          |
| 3  | 900              | 3          |
| 4  | 850              | 2          |
| 5  | 600              | 4          |
| 6  | 125              | 5          |

Table1 模型页面:

public $belongsTo = [
    'pro_relation' => [
        'models\Model',
        'key' => 'id',
        'otherKey' => 'product_id',
    ],

需要正确排列的排序部分:

$query->whereHas('pro_relation', function($q) use ($postFrom,$postTo){
    $q->select('example_relation END AS expose');
})->orderBy("expose", DESC);

【问题讨论】:

  • 你想按什么排序?
  • @AnuratChapanond 是的,我想使用 order by
  • 但是你想要的结果到底是什么?按 example_relation 字段排序?
  • @AnuratChapanond 是的,我想按 example_relation 对产品进行排序。

标签: laravel octobercms


【解决方案1】:

好的,当您想从另一个表中订购一个表的结果时,您可以在与另一个表的关系闭包中使用orderBy()

所以从您的查询中,您可以像这样添加 orderBy()。

$query->whereHas('pro_relation', function($q) use ($postFrom,$postTo){
    $q->select('example_relation END AS expose')
        ->orderBy('example_relation');
});

【讨论】:

  • SQLSTATE[42S22]:未找到列:1054 未知列在“顺序子句”中“公开”(SQL...
  • 我只是从您的代码中复制 ->orderBy("expose", DESC) ,这会导致此错误。
  • 我知道它给出了这个错误,因为定义的暴露不在 table1 中,但如果是这样,我该怎么做?
  • 我看到你从 example_relation 定义了暴露,那么你可以安全地删除 ->orderBy('expose'...) 因为我们已经在闭包中添加了 ->orderBy('example_relation')。
  • 因为我在那里使用了不同的案例结构,所以我在示例中给出了这样的例子。但是,当您按您说的做时,它仍然无法识别“example_relation”列。
【解决方案2】:

这是工作

$query->join('table2', 'table1.id', '=', 'table2.yacht_id')
       ->orderBy(example_relation DESC);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多