Skip to content

Instantly share code, notes, and snippets.

@jamband
Last active August 19, 2016 23:14
Show Gist options
  • Save jamband/1447356 to your computer and use it in GitHub Desktop.
Save jamband/1447356 to your computer and use it in GitHub Desktop.
Yii Framework: example LIKE query.
<?php
$c = new CDbCriteria();
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t`
$c = new CDbCriteria();
$c->addSearchCondition('t.fuga', null); // null, false, ''などは無視されるようです
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t`
$c = new CDbCriteria();
$c->addSearchCondition('t.fuga', 'a');
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t` WHERE t.fuga LIKE :ycp0. Bound with :ycp0='%a%'
$c = new CDbCriteria();
$c->addSearchCondition('t.fuga', 'a%', false);
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t` WHERE t.fuga LIKE :ycp0. Bound with :ycp0='a%'
$c = new CDbCriteria();
$c->addSearchCondition('t.fuga', 'a');
$c->addSearchCondition('t.piyo', 'd');
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t` WHERE (t.fuga LIKE :ycp0) AND (t.piyo LIKE :ycp1). Bound with :ycp0='%a%', :ycp1='%d%'
$c = new CDbCriteria();
$c->addSearchCondition('t.fuga', 'a', true, 'OR');
$c->addSearchCondition('t.piyo', 'd', true, 'OR');
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t` WHERE (t.fuga LIKE :ycp0) OR (t.piyo LIKE :ycp1). Bound with :ycp0='%a%', :ycp1='%d%'
$c = new CDbCriteria();
$c->compare('t.fuga', 'a', true, 'OR');
$c->compare('t.piyo', 'b', true, 'OR');
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t` WHERE (t.fuga LIKE :ycp0) OR (t.piyo LIKE :ycp1). Bound with :ycp0='%a%', :ycp1='%b%'
Hoge::model()->findAll('t.fuga LIKE :fuga', array(':fuga' => '%a%'));
// SELECT * FROM `hoge` `t` WHERE t.fuga LIKE :fuga. Bound with :fuga='%a%'
Hoge::model()->findAll(array(
'condition' => 't.fuga LIKE :fuga',
'params' => array(':fuga' => '%a%'),
));
// SELECT * FROM `hoge` `t` WHERE t.fuga LIKE :fuga. Bound with :fuga='%a%'
$c = new CDbCriteria();
$c->condition = 't.fuga LIKE :fuga';
$c->params = array(':fuga' => '%a%');
Hoge::model()->findAll($c);
// SELECT * FROM `hoge` `t` WHERE t.fuga LIKE :fuga. Bound with :fuga='%a%'
@vovando
Copy link

vovando commented Jul 8, 2016

Thanks! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment