Answer the question
In order to leave comments, you need to log in
What is the best database access method to use in Yii2?
Hello. I recently started learning the wonderful Yii2 framework. The instructions indicate several ways to select from the database. You can use the query builder, you can use ActiveRecord. In the first case, I can make a query like this:
$data= (new Query())
->select(['title', 'text', 'category'])
->from('Posts')
->leftJoin('category', 'posts.id_categoryes = category.id_category')
->all();
<?php foreach ($data as $key => $row): ?>
<?= $row['title']?>
<?= $row['category']?>
<?= $row['text']?>
<?php endforeach ?>
$data = Posts::find()->all();
public function getIdCategoryes()
{
return $this->hasOne(Category::className(), ['id_category' => 'id_categoryes']);
}
<?php foreach ($data as $key => $row): ?>
<?= $row['title']?>
<?= $row->idCategoryes->category;?>
<?= $row['text']?>
<?php endforeach ?>
Answer the question
In order to leave comments, you need to log in
If these are single objects, you can safely use ActiveRecord. The brevity of the code and the convenience of writing and maintaining the code outweighs a small overhead in creating objects (which, in practice, will not play any role).
In general, there is almost no difference between using a "query builder" and using AR, except to use DAO - a small add-on over PDO, which is available through Yii::$app->db (that is, a standard database connection component) .
But if there are dozens and hundreds of objects, I usually use asArray()->all(); to get the result from the table in the form of arrays. This covers 95% of the necessary code for working with databases (well, I think). If you need a lower-level interface, you can always define a method in the AR object that will return the necessary data, and the necessary request will occur inside it.
By the way, I advise you to enable caching of table schemas - it helps a lot in speeding up AR in the future.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question