Custom Query with Cdbcriteria - yii

How can I execute this query with CDbCriteria and CActiveDataProvider?
'SELECT * FROM tbl_post where title LIKE %'.$title.'% ORDER BY title LIKE '.$title.' DESC , title LIKE '.$title.'% DESC'
update:
finaly I wrote this:
$criteria = new CDbCriteria;
$criteria->addCondition('title LIKE :title');
$criteria->params = array(':title'=>'%'.$title.'%',':t1'=>$title,':t2'=>$title.'%');;
$criteria->order='title LIKE :t1 DESC , title LIKE :t2 DESC';
but I got error:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: SELECT COUNT(*) FROM `tbl_post` `t` WHERE title LIKE :title

Try using compare clause, not sure is it you want with the 'order by x like' :
<?php
$criteria = new CDbCriteria;
$criteria->compare('title', $title, true);
$criteria->order = 'title DESC';
$dp = new CActiveDataprovider('posts', array(
'criteria' => $criteria
));

This can be achieved like this:
$dataProvider=new CActiveDataProvider('tbl_post', array(
'criteria'=>array(
'condition'=>'title LIKE % '.$title.' %',
'order'=>'title DESC',
),
));
$dataProvider->getData();
also refer : Help
Thanks.

Related

yii2. query with like condition

In my yii2 application i need something like this:
SELECT * FROM customers WHERE first_name||' '||last_name ILIKE '%Nick%' ORDER BY "id";
This query gets customers with concatinated first_name and last_name like 'Nick'.
In my yii1 application I can use CDBCriteria next way:
$criteria = new CDbCriteria;
$criteria->addSearchCondition(
"first_name||' '||last_name",
'Nick',
true,
'and',
'ILIKE'
);
$criteria->order = 't.id asc';
And this works fine.
In yii2 I tried:
$a = \common\models\Customer::find()
->filterWhere(['ILIKE', "first_name||' '||last_name", 'Nick'])
->orderBy(['id' => SORT_ASC])
->all();
And got exception column does not exist, and sql was:
SELECT * FROM "customers" WHERE "first_name||' '||last_name" ILIKE '%Nick%' ORDER BY "id"
Using \yii\db\Expression doesnt change situation.
Let it be for a while:
\common\models\Customer::find()
->where("first_name||' '||last_name ilike '%'||:query||'%'", [':query' => $name])
->orderBy(['id' => SORT_ASC])
->all()
This is one of many ways to do it:
$customers = \common\models\Customer::find()
->select('*')
->where(['like','concat(first_name,\' \', last_name)','Nick N'])
->orderBy(['id' => SORT_ASC])
->all();

how to convert query with multiple group by columns to CActiveDataProvider in Yii 1.1.14?

I need to conver this sql statement that has a multi column group by clause into CActiveDataProvider in Yii version 1.1.4?
select * from my_table_name group by bookname,categorytitle,bookkey order by bookname,categorytitle,bookkey asc;
I need a CActiveDataProvider to feed a CGridView search function. Apparently, I only have a simple return in my model of the search function that runs my CGridView
return new CActiveDataProvider(get_class($this),
array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'id ASC'
),
'pagination' => array('pageSize' => ActiveRecord::PAGE_SIZE),
));
so how to convert the sql statement that I gave into CActiveDataProvider format ?
You can do using two way -
Make sql view and than create yii model and use this in your
controller or page view.
Create custom search function in your existing model and use group by
e.g. -
<?php
public function new_search(){
$criteria = new CDbCriteria();
...
..
$criteria->group = "bookname, categorytitle, bookkey";
$criteria->order = "bookname, categorytitle, bookkey";
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array('pageSize'=>100)
));
}
?>

count and sort in cgridview getValidators error

I'm getting an error when i add in STAT. I'm trying to count the number of responses for each user and sort it from desc order.
My error: CActiveDataProvider and its behaviors do not have a method or closure named "getValidators".
relation:
'stickerCount'=>array(self::STAT, 'UserSticker', 'user_id'),
controller:
$likes=new CActiveDataProvider('UserSticker');
$this->render('index',array(
'likes'=>$likes,
'sort'=>array(
'defaultOrder'=>'stickerCount DESC',
),
));
<?php
$this->widget ( 'bootstrap.widgets.TbGridView', array (
'id'=>'follower',
'type'=>'striped condensed',
'dataProvider'=>$likes,
'filter'=>$likes,
'columns'=> array(
'stickerCount',
)));
?>
try this:
$criteria = new CDbCriteria();
$criteria->join = 'JOIN (SELECT user_id, count(*) As stickerCounter '
. 'FROM user_sticker GROUP BY user_id) userSticker '
. 'ON userSticker.user_id = t.id';
$likes = new CActiveDataProvider('MainTable',array(
'criteria'=>$criteria,
));
...

how to get data from inner join using cdbcriteria in yii?

This is my SQL. I want to create a CDbCriteria in Yii.
select us.user_id,u.clientid from user_session us
inner join user u on u.id=us.user_id
where us.auth_token='authtoken0000000001'
I tried this, but gives the wrong result. I also defined a relation related in my user_session model for this.
$criteria = new CDbCriteria;
$criteria->select = "user_id,user.clientid as client_id";
$criteria->condition='auth_token="'.$token.'"';
$clientIdarray = UserSession::model()->with('related')->find($criteria);
$dataprovider=New CActiveDataProvider('Bla',
array(
'criteria'=>array(
'order'=>'id ASC',
'with'=>array(
'user',
),
'joinType'=>'INNER JOIN',
'condition'=>'user.auth_token = '.$token,
)
));
Just an example how to do dataprovider init.
$criteria->with do what you need.
This topic will help. http://www.yiiframework.com/doc/guide/1.1/en/database.arr

Use column alias in dataProvider

In my model I have a relation() like this.
'notRelUser' => array(
self::HAS_MANY,
'LocationUser',
'location_id',
'condition' => 'notRelUser.status is null',
'on' => 'notRelUser.user_id = ' . Yii::app()->user->getId(),
'with' => array('parent_location'),
'select' => array('*', 'name AS canApply'),
),
and this
public $canApply;
In my controller I have this
$regions = Location::model()->with('notRelUser')->findAll();
$arrayCanApply = new CArrayDataProvider($regions);
I then am trying to print out the value of canApply in a widget for datagrid
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider'=>$arrayCanApply,
'columns'=>array(
array('name'=>'name', 'header'=>'Name'),
array('name' => 'canApply', 'value'=>'$data->canApply', 'header'=>'CanApply'),
),
));
But the column with canApply is empty.
I have also tried without the $data-> part.
How can I print this alias?
(I know the value of the alias i trivial, but I will change that later)
UPDATE:
I can get the value by using select in CDbCriteria - but I want to do it in relation.
This does work.
$criteria = new CDbCriteria;
$criteria->select = '("foobar") AS canApply';
$regions = Location::model()->with('notRelUser')->findAll($criteria);
but it seems odd that I have to create a $criteria on everytime
you need to declare can canApply as an attribute of the model
in your model decalare canApply as an attribute
public $canApply;
I also had the same problem. Try 'value'=>'$data->notRelUser->canApply'
instead of 'value'=>'$data->canApply'. Also, you need to declare attribute
public $canApply;
in your LocationUser model, not in Location model.