Yii CDbCriteria compare 2 attributes to a single value - php

Hi I am new to yii and I am currently working on a project and I am having trouble with CDbCriteria.
My target query is:
title LIKE '$_GET['search']%' OR description LIKE '$_GET['search']%'
Is it possible to attain same result like this using CDbCriteria compare?
Controller action :
public function actionClassifieds(){
$model = new Classifieds('search');
$model->unsetAttributes();
if(isset($_GET['category'])){
if( $_GET['category'] == 0 ){
$model->classified_category_id = '';
}else{
$model->classified_category_id = $_GET['category'];
}
}
if(isset($_GET['search'])){
$model->title = $_GET['search'];
$model->description = $_GET['search'];
}
$this->render('classifieds',array('model'=>$model));
}
My model:
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('classified_category_id',$this->classified_category_id);
$criteria->compare('title',$this->title,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('price',$this->price,true);
$criteria->compare('timestamp',$this->timestamp);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>10,
),
));
}

Try:
$criteria->condition = "title LIKE :t OR description LIKE :d";
$criteria->params = array(
':t' => trim( Yii::app()->request->getParam('search') ).'%',
':d' => trim( Yii::app()->request->getParam('search') ).'%');
Better using Yii::app()->request->getParam($var_name)
UPDATED
$criteria->compare('classified_category_id',$this->classified_category_id);
$criteria->compare('price',$this->price,true);
$criteria->compare('timestamp',$this->timestamp);
$criteria->addCondition("title LIKE :t OR description LIKE :d");
$criteria->params[':t'] = $this->title;
$criteria->params[':d'] = $this->description;

Related

How to define model parameter value in Yii?

I have a user table in which i have multiple roles and i am showing different user on different action by using same model search function. By this
public actionAdmin(){
$model = new User('search')
$model->unsetAttributes();
$model->userRole = UmsConfing::ADMIN;
if(isset($_GET('User')))
$model->attributes = $_GET['User'];
$this->render('userlist',arary('model'=>$model));
}
I am using this function for different roles .This works well. but now i want to show admin and operation user in same list i tried
$model->userRole = UmsConfig::ADMIN || UmsConfig:: OPERATION
but i didn't work Please help.
Please you can try this below code:
public actionAdmin(){
$model = new User('search')
$model->unsetAttributes();
if(isset($_GET('User')))
$model->attributes = $_GET['User'];
$this->render('userlist',arary('model'=>$model));
}
Below codeadd in User Model Search Function:
model/User.php
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->addInCondition('userRole', array (UmsConfig::ADMIN,UmsConfig:: OPERATION));
$criteria->compare('status',$this->status);
$criteria->compare('is_deleted',$this->is_deleted);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => yii::app()->params->pagesize,
),
'sort'=>array(
'defaultOrder'=>array(
'id'=>CSort::SORT_DESC
),
),
));
}

Yii - findAll with order by

How to findAll with specific column with order by desc ?
Code bellow worked and find all from the developer id
$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id);
Code bellow worked and ordered
$models = Games::model()->findAll(array('order'=>'status'));
When I mixed together then only worked for findAll developer_id='.$id doesn't order by
$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id,array('order'=>'status'));
Any suggestion to do that ? Thanks
In your model, add this function:
public function scopes() {
return array(
'bystatus' => array('order' => 'status DESC'),
);
}
Now you can do the query like this:
$models = Games::model()->bystatus()->findAll('developer_id='.$id);
=====
Bonus: You can also add this function in your model:
public function bydeveloper($devId) {
$this->getDbCriteria()->mergeWith(array(
'condition' => 'developer_id = '.$devId,
));
return $this;
}
Now you can do the query like this:
$models = Games::model()->bystatus()->bydeveloper($id)->findAll();
you can try this -
$id = Yii::app()->user->getState('id');
$model = Games::model()->findAll(array("condition" => "developer_id = '".$id."'","order" => "status"));
its should be work
You can try use criteria:
$id = Yii::app()->user->getState('id');
$criteria=new CDbCriteria;
$criteria->compare('developer_id',$id);
$criteria->order='status DESC';
$models = Games::model()->findAll($criteria);
It's not the best way but you can do:
$models = Games::model()->findAll('developer_id='.$id.' order by status DESC');
Model::find()->where([['attribute'=>'value']])->orderBy(['attribute'=>SORT_DESC])->all();

sorting to DASC does not work in Yii?

$model = new TableName('search');
$criteria = new CDbCriteria;
$criteria->order = 'id DESC';
$model = $model->findAll($criteria);
$model->unsetAttributes(); // clear any default values
if (isset($_GET['TableName']))
$model->attributes = $_GET['TableName'];
$this->render('TableNameView', array(
'model' => $model,
));
after use this code gets a white screen, no any action, and it should sort the why this is happening and how can I fix this way?
You override the original value of $model variable.
$model = $model->findAll($criteria);
After that $model is not an instance of TableName anymore! findAll returns a list of TableName's. So, you must iterate throught this list to get a single instance of TableName.
$models = $model->findAll($criteria);
foreach( $models as $model ) {
// do something with $model
}
Or, if you just need to get the last record, you can use find:
$criteria = new CDbCriteria;
$criteria->order = 'id DESC';
$model = $model->find($criteria);

Using Yii Model and Criteria on CGridView

I'm trying to use my model with a replacement for the search (custom search function):
public function combineCampInputByDate($startDate,$endDate) {
$criteria=new CDbCriteria;
$criteria->select = 'food.*,SUM(customer) AS customer, SUM(money) AS money';
$criteria->join = 'JOIN foodType food ON foodtype = food.foodtype ';
$criteria->condition = "date BETWEEN '$startDate' AND '$endDate'";
$criteria->group = 'foodtype ';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
the result will be the attributes for the model + the other table.
i'm trying to display them in the view but it states no such attribute as .... (this is clear since the model doesnt have an attribiute that came from the other table)
So how do i use the widget below on the model result??
frustrates, but counting on the experts :)
Danny
Edit:
1. Controller -
public function actionIndex()
{
if (isset($_POST['Filter']) && !empty($_POST['Filter']['date']) ) {
$GetDates = new GetDates();
$this->dates = $GetDates->getDatesFromPostWidget($_POST);
$model = new Campaigns;
}
else
$model=NULL;
$this->render('index',array(
'model' => $model, 'dates' => $this->dates,
));
}
Model -
public function combineCampInputByDate($startDate,$endDate) {
$criteria=new CDbCriteria;
$criteria->select = 'food.*,SUM(customer) AS customer, SUM(money) AS money';
$criteria->join = 'JOIN foodType food ON foodtype = food.foodtype ';
$criteria->condition = "date BETWEEN '$startDate' AND '$endDate'";
$criteria->group = 'foodtype ';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
View
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'bo-campaigns-grid',
'dataProvider'=>$model->combineCampInputByDate($dates['startDate'],$dates['endDate']),
'filter'=>$model,
),
));
}
In your model class create two attributes: public $customer and public $money.
You can have as many custom attributes as you want, just be consistent with the naming. (You can't use the SQL fieldname AS something if you don't have a something model attribute first)
EDIT: You should also tell the CGridView which columns to display, like this
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'bo-campaigns-grid',
'dataProvider'=>$model->combineCampInputByDate($dates['startDate'],$dates['endDate']),
'filter'=>$model,
'columns'=>array(
'customer',
'money',
//etc. for more detailed customization, check the links above
),
),
));
}

how to use both condition() and addcondition() for a same search model

I have a grid view with a condition "upload_date = today", but when I search for other dates it is not filtering the grid. Here is my model:
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$date=date('Y-m-d');
$criteria=new CDbCriteria(array('order'=>'upload_date ASC'));
$criteria->condition = "upload_date='$date' ";
if(isset($_GET['upload_date']))
{
$criteria->addCondition('upload_date = :upload_date','AND');
$criteria->params[':upload_date'] = $this->upload_date;
}
$criteria->compare('book_id',$this->book_id);
$criteria->compare('date_received',$this->date_received,true);
$criteria->compare('batch',$this->batch,true);
$criteria->compare('isbn_no',$this->isbn_no,true);
$criteria->compare('book_title',$this->book_title,true);
$criteria->compare('auther_name',$this->auther_name,true);
$criteria->compare('upload_date',$this->upload_date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50
),
));
}
I am trying to use both condition and addcondition in same search. What did I do wrong in the model above?
Try this:
public function search()
{
$criteria=new CDbCriteria(array('order'=>'upload_date ASC'));
if(isset($_GET['ModelName']['upload_date']))
{
$criteria->compare('upload_date',$this->upload_date,true);
// $criteria->addCondition('upload_date = :upload_date');
// $criteria->params[':upload_date'] = $this->upload_date;
}
else
{
$date=date('Y-m-d');
$criteria->condition = "upload_date='$date' ";
}
$criteria->compare('book_id',$this->book_id);
$criteria->compare('date_received',$this->date_received,true);
$criteria->compare('batch',$this->batch,true);
$criteria->compare('isbn_no',$this->isbn_no,true);
$criteria->compare('book_title',$this->book_title,true);
$criteria->compare('auther_name',$this->auther_name,true);
$criteria->compare('upload_date',$this->upload_date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50
),
));
}
You don't need addCondition, specially because you are adding a condition to the same column.
Edit:
In your main initial condition you have already set upload_date = $date, now if you add condition to it, say $_GET['ModelName']['upload_date'] provided by the user in the filter, your actual db query will become something like select * from tbl_name where upload_date = 'xxx' and upload_date = 'yyy' , here xxx=$date you gave, and yyy=date provided by user. Now if xxx != yyy, how will the query return any value? It is not possible.
Hope you got this explanation.

Categories