Answer the question
In order to leave comments, you need to log in
Yii2, activerecord cons of asArray()?
Hello!
Not so long ago, a colleague and I had a dispute about how best to work with ActiveRecord in Yii2, and in particular with the asArray();
.
My colleague suggested to always or most often use this method when getting data from MySQL and build queries in such a way that you would always get a flat array with the desired data, similar to this
array(
'id'=>1,
'name'=>'SomeName',
'subscribers'=>1,
'likes'=>5,
);
the keys 'subscribers' and 'likes' are leftjoin to another table
asArray();
obviously looks much more preferable, because really, why do we need the data that the ActiveRecord model stores, information about behavior and so on. // asArray();
foreach($model as $user){
<p><?= $user['name'] ?><p/>
<p><?= $user['subscribers'] ?><p/>
<p><?= $user['likes'] ?><p/>
}
// Object
foreach($model as $user){
<p><?= $user->name ?><p/>
<p><?= $user->subscribers->value ?><p/>
<p><?= $user->likes->value ?><p/>
}
Answer the question
In order to leave comments, you need to log in
To use asArray() means to lose all the OOP goodies. Do not forget that in addition to the fields in the mods, there is also logic. You don't even have autocomplete buder tabot.
In my opinion, there is no need to choose. Sometimes you need to use an array, sometimes an object. Everything depends on the situation. I think it's more convenient to initially work with objects, and then add asArray when possible when optimizing.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question