Menus

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" ])
->all();
Using between 

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

$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.
User::find()
    ->where( [ 'id' => 1 ] )
    ->exists(); 


 if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
                    {
                        
                        ....... 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();

or

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

or

$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])
->orderBy('staff_name')
->all();
                                         
                   
                     foreach ($teachers as $value) {
                         echo $value['staff_name'];
                     }










No comments:

Post a Comment