Problem with model findallbypk

Hello Gurus!

Hopefully you people can give me a hand in solving this problem. Maybe I am going YII blind at the moment which means that I am simply overlooking the obvious. If so you can flame me ::)

My application is reading records from a database with two PK columns.

I have a controller where I have the following code:




$keyArray['Code'] = 1;

$keyArray['TimePeriod'] = 5;

$returnRecords = MyDbModel::model()->findAllByPk( $keyArray );   


/*Now I loop over the array of ActiveRecords to print what's inside*/

$myFile = "C:\\aaa.txt";

$fh = fopen($myFile, 'w') or die("can't open file");

fwrite($fh, "returnRecords: " . $returnRecords . "\n"); 

fwrite($fh, "count: " . count($returnRecords) . "\n");  


foreach($returnRecords as $fieldList => $value){

    fwrite($fh, "field: " . $fieldList . "\n");  

    fwrite($fh, "value: " . $value . "\n");  

}

				

fclose($fh); 




The output is as follows:

returnRecords: Array

count: 1

field: 0

I am using the print to file to see what’s inside the array. This is not what I expected. I do expect 1 row/record but why is field ‘0’?

When I use findByPK instead, i get nothing even though the 2 keys together are unique.

What am I doing wrong? I have never had problems reading records from the database before. This is the first table that has 2 primary keys, however. Might my problems have something to do with that?

Thank you in advance!

I think you mixed few things together…

fist of all: you should rather call findByPk (not findAllByPk), because you are fetching single record only (at least as I understand your code) - then you do not have to iterate array of objects but you will have only single object (or null when not found). just write:




$record = MyDbModel::model()->findByPk( $keyArray ); //use array because you have composite PK



second: if you are using findAll* method - you receive array of objects of MyDbModel class. So:




$returnRecords = array( MyDbModel, MyDbModel, MyDbModel ... );



Use this function if you do not have composite PK but only trying to fetch list of objects matching fields (findAllByAttributes).

Then, if you want to iterate every attribute of every object you have to:




foreach( $returnRecords as $record ) {

   foreach( $record->attributes as $field=>$value ) {

      echo "$field = $value\n";

   }

}



Hi redguy,

Apparently it was a typical Monday morning issue. Yesterday I tried


MyDbModel()->findByPk( $keyArray )

and I got no result. Zero records. Today I receive my record on a silver platter… Hell if I know what went wrong yesterday! Thank you very kindly for your response!

  • xajaccio