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

时间:2016-11-16 16:47:39

标签: cakephp pagination cakephp-3.x

  • 订购HasOne Suborder
  • Suborder BelongsTo Order

我需要按Suborders中的字段对Orders进行排序,但是按照虚拟字段排序似乎已在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在初始查询中包含Suborder以进行排序和分页?

编辑:

    $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行wheles或者Wheres进行修改,并根据许多条件进行连接。

1 个答案:

答案 0 :(得分:4)

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

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

另见