S
S
Sergey Popov2018-08-17 15:35:51
Laravel
Sergey Popov, 2018-08-17 15:35:51

Display a list sorted by model?

Hello.
I just can’t figure out how to display the sorted values ​​in the form without a large number of queries to the database

Model
-rule
-rule
-rule
Model#2
-rule

In general, I get from the database (model with the Rules (`rule`, `modelNameString`)following query
Rule::orderBy('model', 'asc')->get();
Example result:
[
    {
         'rule' => 'news-create',
         'model' => 'News'
    },
    {
         'rule' => 'news-update',
         'model' => 'News'
    },
    {
         'rule' => 'comment-create',
         'model' => 'Comment'
    }
]

Gotta bring it out
News
-news-create
-news-update
Comment
-comment-create

Required to display a list of checkboxes.
PHP tag, as it is possible to do this with vanilla PHP, probably.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Popov, 2018-08-17
@be_a_dancer

Decided for those who are interested.
I used the laravel functionality, but you can do it with regular arrays.

$initial = $model->get();
$transformed = [];

$initial->transform(function ($item, $key) use (&$transformed) {
    if(!isset($transformed[$item->model]){
        $transformed[$item] = collect();
    }

    $transformed->push($item);
});

In the case of regular PHP, it is enough to use the array_map() function instead of $collection->transform() and arrays instead of collections.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question