产品在Laravel中是如何按关系排序的?



如何根据与表2的连接对表1中的产品进行排序,即根据表2中的example_relation对表1中的产品进行排序?

Table1

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

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

表1模型页:

public $belongsTo = [
'pro_relation' => [
'modelsModel',
'key' => 'id',
'otherKey' => 'product_id',
],

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

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

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

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

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

这是工作

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

最新更新