How to sort collection highlighting by multiple columns in Laravel 5.1?

I have an instance of the Laravel Illuminate collection. An array contains several properties.

I need to be able to sort the collection based on two different attributes.

I want to sort the attribute first, which is called "sort", and then the attribute "title".

Also, I have another collection that I like to sort by sort column if the sort value is not null, and then shuffle the elements for which the null value is sort.

How can I do this type of sorting?

+4
source share
3 answers

Collection::sort:

$collection->sort(function($a, $b) {
   if($a->sort === $b->sort) {
     if($a->title === $b->title) {
       return 0;
     }
     return $a->title < $b->title ? -1 : 1;
   } 
   return $a->sort < $b->sort ? -1 : 1;
});

.

+8

PHP 7, :

$collection->sort(function ($a, $b) {
    return $a->sort === $b->sort ? $a->title <=> $b->title : $a->sort <=> $b->sort;
});

<=> ( : ). RFC.

+7

( PHP) . , .

->with($relatedTableName) , ->sort(), , , :

$baseTableField = "tableField"; // Field name from primary table/model
$relatedTableMapString = "tableName.tableField"; // Field name from a related table

$collection->with('relatedTableName')->sort(function($a, $b) use ($relatedTableMapString, $baseTableField) {

    $relatedTableName = explode(".", $relatedTableMapString)[0];
    $relatedTableFieldName = explode(".", $relatedTableMapString)[1];

    if($a->$relatedTableName->$relatedTableFieldName === $b->$relatedTableName->$relatedTableFieldName) {
        if($a->$baseTableField === $b->$baseTableField) {
            return 0;
        }
        return $a->$baseTableField < $b->$baseTableField ? -1 : 1;
    }
    return $a->$relatedTableName->$relatedTableFieldName < $b->$relatedTableName->$relatedTableFieldName ? -1 : 1;
});
0

Source: https://habr.com/ru/post/1615914/


All Articles