I
I
Ilya Shabanov2012-03-13 15:08:53
Yii
Ilya Shabanov, 2012-03-13 15:08:53

Need help with yii?

There are 2 tables:

CREATE TABLE IF NOT EXISTS `cf_post` (<br>
 `id` int(11) NOT NULL auto_increment,<br>
 `title` varchar(128) NOT NULL,<br>
 `content` text NOT NULL,<br>
 `tags` text,<br>
 `status` int(11) NOT NULL,<br>
 `create_time` int(11) NOT NULL,<br>
 `update_time` int(11) NOT NULL,<br>
 `author_id` int(11) NOT NULL,<br>
 PRIMARY KEY  (`id`)<br>
) ENGINE=MyISAM DEFAULT CHARSET=utf8;<br><br>
CREATE TABLE IF NOT EXISTS `cf_comment` (<br>
 `id` int(11) NOT NULL auto_increment,<br>
 `content` text NOT NULL,<br>
 `status` int(11) NOT NULL,<br>
 `create_time` int(11) NOT NULL,<br>
 `author` varchar(128) NOT NULL,<br>
 `email` varchar(128) NOT NULL,<br>
 `url` varchar(128) NOT NULL,<br>
 `post_id` int(11) NOT NULL,<br>
 PRIMARY KEY  (`id`)<br>
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

And 2 models are interconnected.
Post Model:
public function relations()<br>
 {<br>
  return array(<br>
   'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),<br>
  );<br>
 }

Model Comments:
public function relations()<br>
 {<br>
  return array(<br>
   'post' => array(self::BELONGS_TO, 'Post', 'post_id'),<br>
  );<br>
 }

I'm trying to get a list of posts and comments related to a post:
$dataPosts = Post::model()->with('comments')->findAll();<br>
$dataComments = $dataPosts->comments;

But $dataComments thus comes as NULL.
If making a request
$dataPosts = Post::model()->with('comments')->findByPk(1);
then $dataComments is normally filled with comments.
If I do this:
$dataPosts = Post::model()->with('comments')->findAll();<br><br>
foreach($dataPosts as $val)<br>
 {<br>
  echo $val->comments[1]->content;<br>
 }
then it turns out to pull out the comments. The question is how to extract these comments from the $dataComments variable;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hijaq, 2012-03-13
@ishaba

In the first case, an array of post models is obtained in $dataPosts, therefore $dataPosts->comments should not return anything, because you must first get a specific post model and pull comments from it. Which, in fact, is done in the third option. Read more carefully what is the difference between the return result of findAll() and findByPk()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question