Как изменить порядок выполнения запросов MySQL?

Я пытаюсь получить ссылку на предыдущий и следующий узел / миниатюру для своих страниц и заказывать результаты в соответствии с их названиями или URI файлов или именами файлов …

Код запрашивает базу данных и выводит ссылки на предыдущий и следующий узлы в соответствии с идентификаторами узлов (nid, n.nid). Я хочу заказать результаты в соответствии с названием узла (title, n.title), filename (имя файла, f.filename) или даже URI файла (uri, f.uri).

Однако, когда я меняю эту строку:

->orderBy('n.nid', $order) 

чтобы:

 ->orderBy('n.title', $order) 

это не сработает. Единственное различие заключается в том, что он слегка изменяет порядок, если вы переходите от последней страницы в одной галерее изображений к другой, но в других случаях в галереях все одинаково. Проблема в том, что у вас есть одна галерея и вы решили вставить новое изображение через некоторое время. Идентификатор узла теперь полностью отличается от остальных, и этот код не подбирает его.

Я также пытался сменить другие части, где появляется nid , но он не работает. Я полагаю, что для тех, кто лучше понимает MySQL и PHP, это нечто тривиальное, но я застрял в нем несколько часов и буду благодарен за любую помощь.

Вот весь код (от Влада Стратулата, первоначально найденного здесь ):

template.php

 function dad_prev_next($nid = NULL, $op = 'p', $start = 0) { if ($op == 'p') { $sql_op = '>'; $order = 'ASC'; } elseif ($op == 'n') { $sql_op = '<'; $order = 'DESC'; } else { return NULL; } $output = ''; // your node must have an image type field // let's say it's name is IMAGEFIELD // select from node table $query = db_select('node', 'n'); // join node table with image field table $query->leftJoin('field_data_field_IMAGEFIELD', 'i', 'i.entity_id = n.nid'); // join file managed table where all data about managed files stored $query->leftJoin('file_managed', 'f', 'f.fid = i.field_IMAGEFIELD_fid'); $query // select nid and title from node ->fields('n', array('nid', 'title')) // select uri from file_managed (image path) ->fields('f', array('uri')) // select image alt and title ->fields('i', array('field_IMAGEFIELD_alt', 'field_IMAGEFIELD_title')) // where nid "greater than"/"lower than" our current node nid ->condition('n.nid', $nid, $sql_op) // where node type in array('your content types') ->condition('n.type', array('PHOTOS'), 'IN') // where node is published ->condition('n.status', 1) // where requested node has image to display (if you want thumbnail) ->condition('f.uri', '', '!=') // order by nid ->orderBy('n.nid', $order) // limit result to 1 ->range($start, 1); // make query $result = $query->execute()->fetchAll(); foreach ($result as $node) { // theme your thumbnail image $variables = array( // default image style name `thumbnail` // you can use your own by following // admin/config/media/image-styles on your site 'style_name' => 'thumbnail', 'path' => $node->uri, 'alt' => $node->field_IMAGEFIELD_alt, 'title' => $node->field_IMAGEFIELD_title ); $image = theme('image_style', $variables); $options = array( 'html' => TRUE, 'attributes' => array( 'title' => $node->title ) ); $output = l($image, "node/{$node->nid}", $options); } return $output; } 

node.tpl.php

 <?php print dad_prev_next($node->nid, 'p', 0); ?> <?php print dad_prev_next($node->nid, 'n', 0); ?> 

EDIT 2:

Попытка использовать функцию strcmp:

 function dad_prev_next($title = NULL, $op = 'p', $start = 0) { if ($op == 'p') { $strcmp = '1'; $order = 'ASC'; } elseif ($op == 'n') { $strcmp = '2'; $order = 'DESC'; } else { return NULL; } $output = ''; // your node must have an image type field // let's say it's name is IMAGEFIELD // select from node table $query = db_select('node', 'n'); // join node table with image field table $query->leftJoin('field_data_field_IMAGEFIELD', 'i', 'i.entity_id = n.nid'); // join file managed table where all data about managed files stored $query->leftJoin('file_managed', 'f', 'f.fid = i.field_IMAGEFIELD_fid'); $query // select nid and title from node ->fields('n', array('nid', 'title')) // select uri from file_managed (image path) ->fields('f', array('uri')) // select image alt and title ->fields('i', array('field_IMAGEFIELD_alt', 'field_IMAGEFIELD_title')) // where node type in array('your content types') ->condition('n.type', array('PHOTOS'), 'IN') // where node is published ->condition('n.status', 1) // where requested node has image to display (if you want thumbnail) ->condition('f.uri', '', '!=') // order by nid ->orderBy('n.title', $order) // limit result to 1 ->range($start, 1); // make query $result = $query->execute()->fetchAll(); foreach ($result as $node) { // theme your thumbnail image $variables = array( // default image style name `thumbnail` // you can use your own by following // admin/config/media/image-styles on your site 'style_name' => 'thumbnail', 'path' => $node->uri, 'alt' => $node->field_IMAGEFIELD_alt, 'title' => $node->field_IMAGEFIELD_title ); $image = theme('image_style', $variables); $options = array( 'html' => TRUE, 'attributes' => array( 'title' => $node->title ) ); $output = l($image, "node/{$node->nid}", $options); } return $output; } 

В настоящее время ошибок не зарегистрировано, но всегда отображаются одинаковые фотографии – 2 из первых и 2 из последних в алфавитном списке.