Sunday, 25 June 2017

Yii2 Database Operations

Using yii2 date range in active record

search between two dates in yii2

Correct way of date range check
$model = ModelName::find()->where(['between', 'date', "2015-06-21", "2015-06-27" ])
Using between 

$query= Stockdistributelog::find();    
$query->andwhere(['between', 'date', date('Y-m-d',strtotime($model->date)),date('Y-m-d',strtotime($model->date_to)) ]);

$programs = Programs::find()->where(['>=', 'close_date', $today])->all();

Check official documentation for more details:

check exist ActiveRecord model in database

How to find record exist in database table ?

Yii2 you can add exists() to your query.
    ->where( [ 'id' => 1 ] )

                        ....... Your code Here ......


exists() return value of true or false.

ActiveRecord model in database

Yii2 Using distinct() in SQL Query

$total = YourMOdel::find()->select('company_name')->distinct()->count();


$teachers= Students::find()->select('employee_teachersid')->distinct()->where(['palce_or_subcenter'=>$model->palce_or_subcenter])->all();


$query = YourMOdel::find()->select(['company_name', 'client_code'])->distinct();

yii2 active record find column not equal

andWhere(['!=', 'field', 'value'])

Yii2 Database Some Example

Example 1

$teachers= Employee::find()->select(['staff_id','staff_name'])->where(['status'=>'Working','ccid'=>$center_id])
                     foreach ($teachers as $value) {
                         echo $value['staff_name'];

No comments:

Post a Comment