Ok, let’s start.
As you already know, in Yii2 you need to return() the result from the action:
return $this->render('index', [
'items' => $items,
'sort' => $sort,
'pages' => $pages,
]);
This doesn’t make much sense, until you do something like this:
$items = ['some', 'array', 'of', 'values' => ['associative', 'array']];
\Yii::$app->response->format = 'json';
return $items;
And - voila! - you have
JSON response right out of the box:
{"0":"some","1":"array","2":"of","values":["associative","array"]}
Ok, seems cool, but what about creating arrays of data?
It’s pretty simple too:
$items = \app\models\MyModel::find()->asArray()->all();
Result (json is off):
Array
(
[id] => 532b436477936
[created_at] => 1395344236
[updated_at] => 1395344236
[weight] => 0
[is_disabled] => 0
[region_id] => 532b3fcbf2353
[slug] =>
[name] => Record #1
[description] =>
[lng] => 37.403118
[lat] => 55.803691
)
Array
(
[id] => 532b436f10ea8
[created_at] => 1395344245
[updated_at] => 1395344245
[weight] => 0
[is_disabled] => 0
[region_id] => 52901b3f81daa
[slug] =>
[name] => Record #2
[description] =>
[lng] => 37.463772
[lat] => 55.808827
)
What asArray() does is telling query builder to forget about ActiveRecord stuff and return plain array from DB.
Using asArray() can improve application performance, it also saves memory a lot.
And yes,
relations are also available:
$items = \app\models\MyModel::find()
->with(['region'])
->asArray()
->all();
Result:
Array
(
[id] => 532b436477936
[created_at] => 1395344236
[updated_at] => 1395344236
[weight] => 0
[is_disabled] => 0
[region_id] => 532b3fcbf2353
[slug] =>
[name] => Record #1
[description] =>
[lng] => 37.403118
[lat] => 55.803691
[region] => Array
(
[id] => 532b3fcbf2353
[created_at] => 1395343322
[updated_at] => 1395343486
[weight] => 10
[is_disabled] => 0
[slug] => moskva
[name] => Region #2
[description] =>
[lng] => 37.619899
[lat] => 55.753676
)
)
Array
(
[id] => 532b436f10ea8
[created_at] => 1395344245
[updated_at] => 1395344245
[weight] => 0
[is_disabled] => 0
[region_id] => 52901b3f81daa
[slug] =>
[name] => Record #2
[description] =>
[lng] => 37.463772
[lat] => 55.808827
[region] => Array
(
[id] => 52901b3f81daa
[created_at] => 1385175881
[updated_at] => 1395007960
[weight] => 10
[is_disabled] => 0
[slug] => ekb
[name] => Region #1
[description] =>
[lng] => 56.84147874956556
[lat] => 60.606141082031165
)
)
What about selecting only a few columns? easily:
$items = \app\models\MyModel::find()
->with(['region' => function($q) {
$q->select(['id', 'name', 'slug']);
}])
->select(['id', 'name', 'region_id'])
->asArray()
->all();
Result:
Array
(
[id] => 532b436477936
[name] => Record #1
[region_id] => 532b3fcbf2353
[region] => Array
(
[id] => 532b3fcbf2353
[name] => Region #2
[slug] => moskva
)
)
Array
(
[id] => 532b436f10ea8
[name] => Record #2
[region_id] => 52901b3f81daa
[region] => Array
(
[id] => 52901b3f81daa
[name] => Region #1
[slug] => ekb
)
)
Cool, huh?