CakePHP 3 按具有 HasOne 关系的关联模型排序

CakePHP 3 Sort by associated model with HasOne relationship

我需要按子订单中的字段对订单进行排序,但在 Cake 中似乎已删除按虚拟字段排序 3.x

OrdersTable.php中,我有

    $this->hasOne('Suborder', [
        'className' => 'Suborders',
        'foreignKey' => 'order_id',
        'strategy' => 'select',
        'conditions' => function ($exp, $query) {
            return $exp->add(['Suborder.id' => $query
                ->connection()
                ->newQuery()
                ->select(['SSO.id'])
                ->from(['SSO' => 'suborders'])
                ->where([
                    'Suborder.order_id = SSO.order_id',
                    'SSO.suborder_type_id in' => [1, 2, 3]
                ])
                ->order(['SSO.id' => 'DESC'])
                ->limit(1)]);
        }
    ]);

OrdersController.php中,我有

    $this->paginate = [
        'limit' => 20,
        'order' => ['id' => 'desc'],
        'sortWhitelist' => [
            'id',
            'title',
            'client_order',
            'substatus',
            'Workflows.order_status_id',
            'Clients.name',
            'ProductTypes.type',
            'Suborder.due_date',
            'Suborder.created',
        ],
    ];

    $orders = $this->paginate($collection);

index.ctp中,我有

    $this->Paginator->sort('Suborder.created', 'Order Placed'),
    $this->Paginator->sort('Suborder.due_date'),

我得到的错误是 Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Suborder.created' in 'order clause'。我如何让 Cake 在排序和分页的初始查询中包含子订单?

编辑:

    $collection = $this->Orders->find()
        ->contain([
            'Clients',
            'CurrentAssignment.Users',
            'Workflows.OrderStatuses.Category',
            'Workflows.OrderStatuses.Departments' => function ($q) use ($uID) {
                return $this->Departments->find()->matching('Users', function ($q) use ($uID) {
                    return $q->where(['Users.id' => $uID]);
                });
            },
            'ClientProducts.ProductTypes',
            'Reviews' => function ($q) {
                return $q->where(['review_type_id is not' => 6]);
            },
            'Reviews.ReviewTypes',
            'PublicNotes',
            'ActiveReview',
            'Suborder',
            'Suborder.SuborderTypes',
            'Suborders.SuborderTypes',
        ]);

$collection修改了150行wheres,orWheres,根据多个条件join。

您已将关联配置为使用 select 策略,该策略将使用单独的查询来检索数据 (currently wrongly documented),因此您无法在用于分页的主查询中引用它.

因此,如果您想对其进行排序,则必须使用默认的 join 策略。

另见