How To Read ActiveRecord(Object)?

I try to understand how to display my ActiveRecord query.

I tried to find help on the subject like here Yii: Active Record, it shows how to make the query but not how to read the result object <_<

I would like to know the basic syntax for ActiveRecord queries.

Simple example:

table: ITEMS

|ID__| Title_____| Desc____| IDcategory__|

|1___| Potatoes__| Vege____| 3___________|

|2___| Steak_____| Beef____| 3___________|

|3___| Car_______| Mechanic| 3___________|

Now I have a query that goes like:

public $listOfItems;

public function fetchList(){

$this->listOfItems = ItemsDB::model()->findAllByAttributes(array('IDcategory'=>3));


Now technically, I should have an AR object with the 3 Items.

But If I want to extract the information to display 3 Items. What’s the standard approach?

I tried the mysql function to at least get the first row:

    $row = mysql_fetch_array($model->listOfItems) or die(mysql_error());

    echo $row['title']. " - ". $row['Desc'];

I got a : [color="#FF0000"]mysql_fetch_array() expects parameter 1 to be resource, array given[/color]

I know it’s basic stuff, but I don’t understand how to extract and display the info from the bloody object :lol:

Thank you for your time :D

You really shouldn’t need mysql_fetch_array. The Yii-AR approach will load rows of a table into an object. So if you’ve got this:


You should be able to do this:


  <?php foreach($items as $item): ?>

    <li><?php echo $item->Title; ?> - <?php echo $item->Description; ?></li>

  <?php endforeach; ?>


Btw: You need to work on your naming conventions.

Please take more time reading the Framework documentation, this will be done as "Da:Sourcerer " wrote (the raw way) or using a CListView, CGridView, or any CHtml method to display a list provining from an array. Take a look at DataProviders too, and how the actions/views/controllers and models interacts…so if you dont read more deeply then you got a very wrong way.

Thank you Da:Sourcerer for your input, it resolved my problem! :lol:

Very interesting bluyell, is "CDataProvider" the standard way to access data?

What’s the official way that pros approach the problem? ::)

Actually, no. CDataProvider is a facility that prepares data from a data source for pagination/sorting/filtering. See CActiveDataProvider and CArrayDataProvider for more.

If you want to see what object or array of objects you get back from Active Records, do this (in your controller)

$itemsDB= ItemsDB::model()->findAllByAttributes(array('IDcategory'=>3));

echo var_dump(itemsDB);

var_dump() shows you everything you want to know, and a whole lot more…