H
H
HellWalk2017-08-01 12:15:32
Yii
HellWalk, 2017-08-01 12:15:32

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();

Option 2
$country = (new Query())
            ->from('country')
            ->select(['name', 'population'])
            ->one();

Update: And a third option, which looks quite hardcore, but which is found in the manuals:
$db = new yii\db\Connection(...);

$posts = $db->createCommand('SELECT * FROM post')
            ->queryAll();

A familiar programmer said that the first one is better, but did not explain why (he said "everyone")

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2017-08-01
@qonand

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

M
Maxim Timofeev, 2017-08-01
@webinar

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).

D
davidnum95, 2017-08-01
@davidnum95

In the first option, it is more convenient to work with connections.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question