ActiveRecord vs QueryBuilder

Hi,

When is recommended to use ActiveRecord, when - QueryBuilder?

Thanks.

Use QueryBuilder when it’s indeed impossible to use ActiveRecord. :)

Use yii\db\Command to execute SQL queries.

Use yii\db\Query to build queries dinamically:




$query = (new Query())->select('*')->from('table');

if ($applyCondition1) {

  $query->where(/*...condition1..*/);

}

if ($applyCondition2) {

  $query->andWhere(/*...condition2..*/);

}



Use Active Record when you need a model object with one or more of the following features:

  • validation

  • lifecycle events

  • calculations (virtual attributes)

Hi, thanks for anwsers! But I don’t understand one thing.

I created to tables:

Users:

id,

username

Comments:

id,

user_id,

comment

I created relation in Users model:




public function getComments()

{

   return $this->hasMany('app\models\Comments', ['user_id' => 'id']);

}



Also I wrote 2 functions:

First:




public function getAllComments()

{

   return Users::find()->all();

}



Second:




public function getAllComments2()

{

   return Users::find()->joinWith('comments')->all();

}



And I get the same result from these functions! So why we need additional joins in ActiveRecord if we can get the same result only with: return Users::find()->all(); ?

Thanks for answer!

These expressions:




return Users::find()->all();






return Users::find()->joinWith('comments')->all();



return same results because joinWith, without other params then relation name, make a left join from primary and secondary table.

http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#joinWith()-detail

So, it will return all rows of first table (Users) and make a join with second table (Comments).

If for example there aren’t record in Comments’ table, it will return anyway all records of User’s table, because it is a LEFT JOIN.

Dude, I get it! Thanks!