Sorting in Yii 2
Sorting in Yii 2

Sorting

When displaying multiple rows of data, it is often needed that the data be sorted according to some columns specified by end users. Yii uses a [[yii\data\Sort]] object to represent the information about a sorting schema. In particular,

  • [[yii\data\Sort::$attributes|attributes]] specifies the attributes by which the data can be sorted. An attribute can be as simple as a model attribute. It can also be a composite one by combining multiple model attributes or DB columns. More details will be given in the following.
  • [[yii\data\Sort::$attributeOrders|attributeOrders]] gives the currently requested ordering directions for each attribute.
  • [[yii\data\Sort::$orders|orders]] gives the ordering directions in terms of the low-level columns.

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



To use [[yii\data\Sort]], first declare which attributes can be sorted. Then retrieve the currently requested ordering information from [[yii\data\Sort::$attributeOrders|attributeOrders]] or [[yii\data\Sort::$orders|orders]] and use them to customize the data query. For example,

use yii\data\Sort;

$sort = new Sort([
    'attributes' => [
        'age',
        'name' => [
            'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
            'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
            'default' => SORT_DESC,
            'label' => 'Name',
        ],
    ],
]);

$articles = Article::find()
    ->where(['status' => 1])
    ->orderBy($sort->orders)
    ->all();

In the above example, two attributes are declared for the [[yii\data\Sort|Sort]] object: age and name.

The age attribute is a simple attribute corresponding to the age attribute of the Article Active Record class. It is equivalent to the following declaration:

'age' => [
    'asc' => ['age' => SORT_ASC],
    'desc' => ['age' => SORT_DESC],
    'default' => SORT_ASC,
    'label' => Inflector::camel2words('age'),
]

The name attribute is a composite attribute defined by first_name and last_name of Article. It is declared using the following array structure:

  • The asc and desc elements specify how to sort by the attribute in ascending and descending directions, respectively. Their values represent the actual columns and the directions by which the data should be sorted by. You can specify one or multiple columns to indicate simple ordering or composite ordering.
  • The default element specifies the direction by which the attribute should be sorted when initially requested. It defaults to ascending order, meaning if it is not sorted before and you request to sort by this attribute, the data will be sorted by this attribute in ascending order.
  • The label element specifies what label should be used when calling [[yii\data\Sort::link()]] to create a sort link. If not set, [[yii\helpers\Inflector::camel2words()]] will be called to generate a label from the attribute name. Note that it will not be HTML-encoded.

Info: You can directly feed the value of [[yii\data\Sort::$orders|orders]] to the database query to build its ORDER BY clause. Do not use [[yii\data\Sort::$attributeOrders|attributeOrders]] because some of the attributes may be composite and cannot be recognized by the database query.

You can call [[yii\data\Sort::link()]] to generate a hyperlink upon which end users can click to request sorting the data by the specified attribute. You may also call [[yii\data\Sort::createUrl()]] to create a sortable URL. For example,

// specifies the route that the URL to be created should use
// If you do not specify this, the currently requested route will be used
$sort->route = 'article/index';

// display links leading to sort by name and age, respectively
echo $sort->link('name') . ' | ' . $sort->link('age');

// displays: /index.php?r=article%2Findex&sort=age
echo $sort->createUrl('age');

[[yii\data\Sort]] checks the sort query parameter to determine which attributes are being requested for sorting. You may specify a default ordering via [[yii\data\Sort::defaultOrder]] when the query parameter is not present. You may also customize the name of the query parameter by configuring the [[yii\data\Sort::sortParam|sortParam]] property.

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu