5

我有一个订购项目列表,根据 int 字段排序order。我在 CakePHP 1.2 中创建了一个画廊,它有一个上一个和下一个按钮,这些应该根据它们的顺序链接到上一个和下一个项目,而不是根据他们的id.

为了得到这个结果,我在 find 函数中包含了 'order' 参数,并用'Item.order'=>'DESC'. 结果仍然是一个id有序列表。

我的问题是:我做错了什么?我的控制器:

$this->Item->id = 16;

$neighbours = $this->Item->find('neighbors', array(
    'order' => array('Item.order'=>'DESC'),
    'fields' => array('id','name')
));

我的解决方案

我尝试了不同的方法。我的代码现在完成了这项工作,如下所示:

$order = $this->Item->findById(6);

$neighbours = $this->Item->find('neighbors', array(
    'field' => 'order',
    'value' => $order['Item']['order']
));

通过将参数设置'field'为字段将是 ordering 字段,并将'value'参数设置为您当前 Item 的 order 值,您将获得prevand next

4

2 回答 2

4

是的,问题是您没有在字段数组中包含订单字段。

$neighbours = $this->Item->find('neighbors', array(
    'order' => 'order DESC',
    'fields' => array('id', 'name', 'order')
));

除非您有具有冲突字段名称的相关模型,否则您不需要包含Item.模型前缀(尽管我通常会这样做以避免此类错误。)如果您包含[Item.]order在“字段”中,您的原始语法将起作用

最后,您的解决方案不是最优的,您在不需要时进行了两个 SQL 查询。据我所知,“字段”不是查询选项,这实际上意味着您要返回表中的所有字段。

于 2011-07-20T08:05:58.843 回答
0

I was having problems with this. Basically I have a list of questions that need to be randomly ordered (once only) per user session.

I was setting the order of the model to something like this:

'FIELD(TestQuestion.id, 3, 1, 5)';

This worked fine for normal queries, but finding neighbors is stymied by line 2897 in Model.php:

$query['order'] = $field . ' DESC';

So to get around it, I did the following:

  • Add a virtual field called 'examination_order', and set the order to that:

    $this->TestQuestion->virtualFields['examination_order'] = 'FIELD(TestQuestion.id, 3, 1, 5)';
    
    $this->TestQuestion->order = array(
        $this->TestQuestion->alias . '.examination_order'
    );
    
  • In the find neighbors call, set the 'field' to 'examination_order', with the value set to the index as found previously:

    $neighbors = $this->TestQuestion->find(
        'neighbors',
        array(
            'field' => 'examination_order',
            'value' => $testQuestion[$this->TestQuestion->alias]['examination_order'],
            'conditions' => $conditions
        )
    );
    
于 2013-11-18T02:51:04.563 回答