Pergunta

Eu tenho uma lista de itens ordenados, ordenados de acordo com o campo int order. Estou criando uma galeria no CakePhp 1.2 que tem um botão Anterior e Próximo e que deve vincular ao item anterior e próximo de acordo com o pedido, não de acordo com o seu id.

Para obter esse resultado, incluí o parâmetro 'Order' para a função de localização e preencher -o com 'Item.order'=>'DESC'. Ainda o resultado é um id Lista ordenada.

Minha pergunta é: o que eu faço de errado? Meu controlador:

$this->Item->id = 16;

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

Minha solução

Eu tentei uma abordagem diferente. Meu código agora faz o trabalho e parece o seguinte:

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

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

Definindo o parâmetro 'field' para o campo será o campo de pedidos e definirá o 'value' Parâmetro para o valor do pedido de seu item atual, você obterá o prev e next.

Foi útil?

Solução

Yeah the problem was that you weren't including the order field in your fields array.

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

Unless you have related models with conflicting field names you don't need to include the Item. model prefix (though I usually do anyway to avoid such errors.) You're original syntax would work if you had included [Item.]order in "fields"

Finally, your solution is not optimal, you're making two SQL queries when you don't need to. and 'field' is not a query option as far as I'm aware which actually means you're returning all of the fields in the table.

Outras dicas

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
        )
    );
    
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top