Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - How to use conditions like where and limit

I use findAll() like this:

$l = SiteContentRelated::model()->findAll('content_1=:c', array(':c' => $id));

How I can add condition to this?

Like as LIMIT 5 or anything?

like image 741
Chalist Avatar asked Dec 31 '12 12:12

Chalist


1 Answers

Use CDbCriteria to specify more detailed criteria:

$criteria = new CDbCriteria;
$criteria->condition = 'content_1=:c';
$criteria->limit = 5;
$criteria->params = array(':c' => $id);

$l = SiteContentRelated::model()->findAll($criteria);

or pass an array to findAll which will be converted to a CDbCriteria:

$l = SiteContentRelated::model()->findAll(array(
  'condition' => 'content_1=:c',
  'limit' => 5,
  'params' => array(':c' => $id),
));

When you specify a LIMIT, it's a good idea to also specify ORDER BY.


For filtering based on model attributes, you can also use findAllByAttributes:

$l = SiteContentRelated::model()->findAllByAttributes(array(
  'content_1' => $id,
), array(
  'limit' => 5,
));
like image 99
DCoder Avatar answered Oct 21 '22 03:10

DCoder