SELECT *
FROM
(SELECT unnest(relation_ids) AS related_id,
id AS parent_id
FROM
(SELECT orders.id,
(SELECT array_agg(distinct(id))
FROM orders AS o_r
WHERE o_r.cost > orders.cost ) AS "relation_ids"
FROM orders) AS orders) AS orders
INNER JOIN "orders" AS "relation_orders" ON "relation_orders"."id" = "orders"."related_id"
public function matchMany($models, $queryResults, $relation, $related, $foreignKey, $primaryKey)
{
$results = $queryResults($models);
$dictionary = $this->buildDictionary($results, $foreignKey);
foreach ($models as $model) {
if (isset($dictionary[$key = $model->getAttribute($primaryKey)])) {
$model->setRelation(
$relation, $this->getRelationValue($dictionary, $key, $related)
);
} else {
$model->setRelation(
$relation, collect([])
);
}
}
return $models;
}
Reverse просто перевернет результат, получится от худших к лучшим