[SOLVED] 'with' in the Model

Rookie question:

I have a model with the following relation:




'articles'=>array(self::BELONGS_TO, 'Article', 'proficiencyId','with'=>'articleReviews'),



I’m using it like this:




$articles = Comments::model()->with('articles')->together()->findAll();



How do I access the ‘articleReviews’ array?

I’ve tried $articles->articles->articleReviews

and

$articles->articles[‘articleReviews’]

but I get the error ‘trying to access property of non-object’.

I can print_r the resultant array and all the data is there in a format that should be accessible with the ‘$articles->articles->articleReviews’ syntax.

Thanks!

I think you got it wrong, you should:

Article -> relatedTo -> ArticleReview by their correspondent foreign key

in Article:




public function relations(){

    return array('reviews'=>array(self::HAS_MANY,'ArticleReview', 'FOREIGNKEYTHATCONNECTSBOTHSTABLES'),);

}



in ArticleReview




public function relations(){

    return array('article'=>array(self::BELONGS_TO, 'Article', 'FOREIGNKEYTHATCONNECTSBOTHSTABLES'),);

}



Then you can call




$articles = Article::model()->with('reviews')->findAll();


// or


$article = Article::model()->findbyPk('thekey');


foreach( $article->reviews as $review ) ...




Or that, or I didn’t understood the question… hope I helped you anyway

I tried your way first but it would not work because the ArticleReview table does not share the same FK as the other two (normaiized DB). The only way to get to the data I need is to use ‘with’ in the model which cascades, for lack of a better word, the relations through the the middle table (Article).

The data does in fact get returned; it just doesn’t seem accessible.

I’m sure I need to use multiple foreach statements to break the arrays up but I just can’t seem to get the right depth.

try




<?php

foreach($articles as $article)

{

 echo $article->reviews ; 

// you might have to do a foreach within this loop because I think the reviews is an array of review objects 

}



Totally untested

doodle




<?php

foreach($articles as $article)

{

 echo $article->reviews ; 

// you might have to do a foreach within this loop because I think the reviews is an array of review objects 

}



Thanks guys, that got me on the right track.

With two foreach it works:




foreach($articles as $article)

  foreach($article->articles->articleReviews as $review)



I was making it more complex than it needed to be.

Your table naming choices make your job of conceptualizing the data an unhappy one.

Those aren’t the actual table names.

/shock

Thanks.