Filtering DB result sets

I basically have an issue that I’m wondering about, first though I will explain my scenario. I have “pages” and associated with each page are multiple “content modules”, stored in a pages and content table with a one to many relationship.

I could simply do everything I need by making a new model every time I need data but if I’m not mistaken this will use another query every time I need a piece of data when I could load a page and all the content in one go.

So my question is, say I have an array of all the content models in $content, ie:




$pagemodel = Pages::model()->findByAttributes(array('pid'=>$pid));

$content = $pagemodel->content;



How can I select an element of that $content array based on one of the properties of one of those instances in the array, I tried:




$content->findByAttributes(array('cid'=>$cid));



but it didn’t work. Is there any way I can filter a database model once it has already been constructed?

In your case, $content is simply an array of model, is not an object at all, so you cannot use any method.

You can do something like:


$content= $magemodel->content(array('condition'=>'cid= $cid'))

In onther words, you can pass an array to the function content that will be used for create a CDbCriteria for filtering the result.

Ahh, right, thanks, will that execute another query or will that work with the data thats already loaded into the model?

It will fire another query, of corse.

If you want to filter all data at once, you have to:


$pagemodel = Pages::model()->find(array('condition'=>"pid= '$pid'", with=>array('content'=>array('condition'=>"cid= $cid'))));

Is a bit more complicated, but maily we are passing the condition to the first find. This will do all in a sigle query

Thanks, thats a great help.

Is there any way I can get it to generate an associative array using a database field as the key when it returns an array of results?

The thing is that I know all the content content rows for a page need to be used so it would be more efficient to fetch them all at once, but I don’t know how to access a row specifically from the pre-prepared array of rows based on a field.

Would the best way to do this be to just use a foreach statement to construct an array from the returned database array? Or is there a cleaner way?

I have no experience of this stuff, but there is this interesting new feature in documentation.

Try it an let us know if it solves (and how).

Thanks, that worked a treat:


$content = $pagemodel->content(array('index'=>'cid'));

Was exactly what I was looking for!

Yeah!

Glad to help you!