Answer the question
In order to leave comments, you need to log in
Which of these methods is better for working with the database?
I delve into working with the database in Yii2, and meeting various options in the manuals, the question immediately arose - which of these methods is better, and than:
Option 1 (through the model)
$query = Country::find();
$country = $query
->from('country')
->select(['name', 'population'])
->one();
$country = (new Query())
->from('country')
->select(['name', 'population'])
->one();
$db = new yii\db\Connection(...);
$posts = $db->createCommand('SELECT * FROM post')
->queryAll();
Answer the question
In order to leave comments, you need to log in
These two methods give a slightly different result - so their comparison is slightly correct.
The first option executes a query and converts its result into an ActiveRecord object, the second one returns the result as an array with data. Which option to use depends on the project and its architecture.
Conclusion - you need to work with database data as with objects - use the first option, you need to work with data as with an array - the second
2nd is faster
1 is more flexible
I find that using a framework is development speed and flexibility. If you bypass objects for the sake of saving pennies, then why the framework in principle? Write in bare php without OOP. If you know for sure that AR is not needed at the moment, the 2nd option is reasonable. If you ask a question in principle - you are engaged in nonsense.
My advice: when developing, use the 1st option everywhere, then when optimizing, where it is possible to replace it with the 2nd one (and if necessary).
In the first option, it is more convenient to work with connections.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question