Bad thing is, we can have some complicated logic inside our models.
For example, our own getters:
public function getCreated()
{
return $this->created_at ? date('d-m-Y', $this->created_at) : null;
}
(okay, that was not complicated, just proving my point)
If only we could convert our models to arrays… Wait! Turns out, we already can do that!
Here’s how it’s done:
$item = \app\models\Region::find($id);
$item->toArray();
Result:
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
)
We can also provide a couple of args to this function to limit number of columns:
$item->toArray(['id', 'name']);
Result:
Array
(
[id] => 52901b3f81daa
[name] => Region #1
)
Notice that if we add our getter to this list, the result does not change (and no notice will be raised):
$item->toArray(['id', 'name', 'created']);
Result:
Array
(
[id] => 52901b3f81daa
[name] => Region #1
)
It’s by design, see this topic.
Anyway, to use our custom fields we need to list this field inside fields() function in our model:
public function fields()
{
return ['id', 'name', 'created'];
}
Now everything is ok:
Array
(
[id] => 52901b3f81daa
[name] => Region #1
[created] => 23-11-2013
)
We can also grab related models, by listing them in fields():
public function fields()
{
return ['id', 'name', 'created', 'region'];
}
Array
(
[id] => 532b436477936
[name] => Record #1
[created] => 20-03-2014
[region] => Array
(
[id] => 532b3fcbf2353
[name] => Region #2
[created_at] => 1395343322
)
)
Or even better (I suppose this is the way it should be done):
we define our custom fields and relations in extraFields()"
public function extraFields()
{
return ['created', 'region'];
}
and then mention them as second argument of toArray():
$item->toArray(
['id', 'name'], // here are our table fields
['created', 'region'] // and here are our custom logic
);
Notice that $item->toArray() without arguments will use defined fields() function or parent implementation of it.