Question

I need the data from various table. I bind them by using cakephp's $hasMany variable. The data is fetched successfully. But I need to sort the result coming from $hasMany table.

for eg. I have two tables

  • Survey
  • Questions

Now Survey table contains the data related to Survey like title, id, purpose and Questions table contains question for related survey. I bind questions table with survey in survey model. Now I have a field in Questions table with name ordering. I need to fetch data in that order.

How can I fetch it in that way?

Please help me.

Était-ce utile?

La solution

If you want to sort the data directly when it is fetched from db

You can define default order when adding relations between tables in your models. In your Survey model:

var $hasMany = array(
    'Question' => array(
        'order' => 'ordering DESC'
    )
);

See http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany.

You can also define custom ordering when retrieving data from your controller in your conditional array, http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find:

$conditions = array(
    'order' => array('Question.ordering DESC')
);

If you are paginating your result with the paginator component, you can setup it like in following example book.cakephp.org/2.0/en/core-libraries/components/pagination.html#query-setup:

public $paginate = array(
    'order' => array(
       'Question.ordering' => 'desc'
    )
);

If you want to sort the data presented in the view

Here you can use the pagination helper (together with the pagination component in the controller) as:

echo $this->Paginator->sort('Question.ordering');

see book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#creating-sort-links

Sorry for removing 'http://' on the two last links, but I am not allowed to post more than two links (<10 rep).

Autres conseils

In CakePHP you can sort by associated tables. but you need to sort by column, you should use something like this in your view:

<?php echo $this->Paginator->sort('Question.ordering'); ?>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top