Let me see
Let me see

Reputation: 5094

How to Store result of a HAS_MANY RELATION database query in yii?

PLEASE HELP....I AM A NEWBIE

I have 2 tables PAGE and COMMENT.

Page table has columns

$id
$user_id 
$content

Comment table has columns

$id
$user_id
$page_id
$date_entered

$comment      **The comment column consist of an array of comments as one user can have many comments** 

In the Page model the relation in the relation() is defined as

return array(
    'comments' => array(self::HAS_MANY, 'Comment', 'page_id')
)

Now in the PageControllor.php,I have defined this query in the actionView()

$page = Page::model()->with('user','comments')->findByPk($id);

Now my question is

how can i get the result of this query in $result so that i could pass it to the view page as

$this->render('view',array('model'=>$this->loadModel($id),'result'=>$result))

Upvotes: 1

Views: 185

Answers (2)

Balaji Viswanath
Balaji Viswanath

Reputation: 1684

To exactly answer your question, all you have to do is,

$this->render('view',array(
    'model'=>$this->loadModel($id),
    'result'=>$page
));

Upvotes: 1

Zack Newsham
Zack Newsham

Reputation: 2992

You havent defined what "this query" is that you want to assign to result.

However, if all you want is to get a list of all the comments associated with a page, all you need to do is this:

foreach($page->comments as $comment){
    ....
}

when calling $this->render do the following:

$this->render('view', array('page'=>$page);

when you assign $page you don't actually need the with method - thats only if you are going to be querying on those fields. So This will suffice:

$page = Page::model()->findByPk($id)

Upvotes: 1

Related Questions