mysql - Create simple query using MongoDB with Yii2 advanced template -


how can build query in yii2 , mongodb:

this yii2 , mysql:

$connection = new query; $sql = "select e.emp_id emp_id, e.full_name full_name, e.email email, e.contact contact, e.address address, e.gender gender, e.avatar avatar, e.status status, date_format(e.added_date_time,'%d/%m/%y %h:%i:%s') added_date_time, d.dept_name dept_name employee e, department d e.dept_id = d.dept_id"; $model = $connection->createcommand($sql); $posts = $model->queryall(); return json_encode($posts); 

but how can create same query in mongodb yii2?
there command createcommand() , pass sql in function?

first of need create model extended yii\mongodb\activerecord.

why not use framework features such activerecord , activequery instead of writing raw sql?

you can write query regular activequery:

use app\models\employee; use yii\db\expression;  ...  employee::find()     ->select([         'emp_id',         'full_name'         'email',         'contact'         'address',         'gender',         'avatar',         'status',         'added_date_time' => new expression("date_format(added_date_time,'%d/%m/%y %h:%i:%s')"),         'dept_name',     ])     ->all(); 

some notes query:

1) it's better create model department , relation if it's needed. current selection 2 tables , condition doesn't make sense because employees returned.

2) because of 1), aliases redundant.

3) of times activerecord don't need explicitly specify selected attributes.

4) it's better format date on server side.


Comments