Cakephp 3 _matching,如何格式化结果数据

Cakephp 3 _matching, how format results data

我的查询如下:

$test = $this->Producers->find()
    ->hydrate(true)
    ->select(['Producers.id','Producers.name', 'Products.id', 'Products.name']);

    $test->matching(
            'Products.Categories', function ($q) {
                return $q->where(['Categories.id' => 22]);
    } );

这个查询使用内连接,返回的数据看起来很自然

|Producers_id|Producers_name|Products_id|Products_name|
-------------------------------------------------------
|1           |Canon         |1          |EOS 1000D    |
-------------------------------------------------------
|1           |Canon         |2          |EOS 300D     |
-------------------------------------------------------
|1           |Canon         |3          |EOS 50D      |
-------------------------------------------------------
|3           |Nikon         |6          |D600         |
-------------------------------------------------------
|3           |Nikon         |7          |D100         |
-------------------------------------------------------

在视图中,每次迭代后我有每一行的生产者和产品:

=============================
Producer: Canon
-----------------------------
EOS 1000D
=============================
Producer: Canon
-----------------------------
EOS 300D
=============================
Producer: Canon
-----------------------------
EOS 50D
=============================

但我希望格式化数据如下:

=============================
Producer: Canon
-----------------------------
EOS 1000D
-----------------------------
EOS 300D
-----------------------------
EOS 50D
=============================
Producer: Nikon
-----------------------------
D600
-----------------------------
D100
=============================

最佳数据格式设置做法是什么?在视图中,还是model/controller?也许使用 mapReduce()?

无论是否采用最佳做法,使用 Cake\Collection\Collection,您都可以对结果进行分组:

$collection = new Collection($test);
$byProducer = $collection->groupBy('Producers_name')->toArray();

这将导致:

[Canon] => Array
    (
        [0] => Array
            (
                [Producers_id] => 1
                [Producers_name] => Canon
                [Products_id] => 1
                [Products_name] => EOS 1000D
            )

        [1] => Array
            (
                [Producers_id] => 1
                [Producers_name] => Canon
                [Products_id] => 2
                [Products_name] => EOS 300D
            ) ...
    )

[Nikon] => Array
    (
        [0] => Array
            (
                [Producers_id] => 3
                [Producers_name] => Nikon
                [Products_id] => 6
                [Products_name] => D600
            ) ...
    )