I have been using Yii for a while now and when I want to pull data from a database I generally just use a findByAttributes.
$model=Auction::model()->findAllByAttributes(array('status'=>'1'));
Or something along those lines.
My question would be, how would I handle a greater than type situation? I tried
$model=Auction::model()->findAllByAttributes(array('starttime'>=$date));
where date had been assigned a current date/time setup however this causes an error. So my question is do I need to use conditions and or params? Should I do this type of thing in the model and or using the Criteria or CActiveDataProvider stuff?
I would appreciate someone pointing me in the right direction. I have always just gotten by using findAll()s but I know their is a better way to do this. Some general info on what and when to use Attributes, Conditions, Params, etc would also be nice.
I have read the Yii documentation and searched tons of sites for the answers to these questions and Im not finding it.
The type of the 2nd parameter of findAllByAttributes
is mixed, thus we have (not infinitely but) many possibilities, for example:
$model = Auction::model()->findAllByAttributes(
array(
'status' => 1
),
'starttime >= :date',
array(
'date'=>$date
)
));
or
$model = Auction::model()->findAllByAttributes(
array(
'status' => 1
),
array(
'condition' => 'starttime >= :date'
'params' => array('date'=>$date)
)
));
It's a good idea to use params even with findByAttributes, but that only does matching. You can use findAll and add a condition statement and the format would be very similar to what you are already doing:
$model=Auction::model()->findAll(array(
'condition'=>'status=:status AND starttime >= :date',
'params'=>array(':status'=>1, ':date'=>$date),
));
If you were doing a very complex query or building a query programmatically you might want to use findAllBySql or CDbConnection::createCommand or Query Builder, it just depends on what makes the most sense for your app.
I would (re)read the Yii section on Working with Databases, while it doesn't have extensive examples, it's pretty clear. Then you can try the Yii Blog tutorial, Larry Ullman's tutorials, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With