S
S
Sergey Brazhnikov2019-07-10 11:14:16
Yii
Sergey Brazhnikov, 2019-07-10 11:14:16

How to sort items by related table field in Yii2?

There are `ProductNomeclature` and `Brand` models. And the `Brand` model has `name` properties.
How to get the sorted rows of the ProductNomeclature table, by the `name` field of the `Brand` model?
The ProductNomeclature table has a "brand_code" field - this is the brand ID of the brand table.
After sampling, of course, I can sort the array, but I need sorting at the sampling stage (SQL query). Sorting an array AFTER the selection, by nested values ​​does not suit me !!
In a query of this kind, the data that is selected from the associated brand table is sorted:

$items = ProductNomeclature::find()
        ->with([
            'brand' => function ($query) {
                $query->orderBy('name', 'ASC');
            }
        ])
        ->all();

But I have a connection from the brand table, for each row of the ProductNomeclature table, only one brand is selected, so sorting is not needed there.
But it is necessary that all rows from the ProductNomeclature are sorted by the 'name' field from the brand table.
This does not work like this:
$items = ProductNomeclature::find()
        ->with(['brand'])
        ->orderBy('name', 'ASC')
        ->all();

Because the 'name' field does not exist in the ProductNomeclature table.
Tried to do it like this: ->orderBy('brand.name', 'ASC') - doesn't work either.
Says that in the ProductNomeclature - the brand.name field does not exist.
In Google rummaged MANY WHERE! - Didn't find anything suitable.
There are options, but for Laravel. They are not suitable for Yii2.
In Yandex, too, I dug a lot where, I did not find anything suitable.
I would be very grateful for your help in solving this problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2019-07-10
@shtepsil

with uses a separate query with IN(), the first query does not know anything about the second table, so you need to remake it for join queries

T
twobomb, 2017-10-02
@campus1

Can be easier

var arr = ;
 var maxarr = arr.map(function(c){
 return Math.max.apply(null, c);
 });
 alert(maxarr );//[27,5,39,1001]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question