Answer the question
In order to leave comments, you need to log in
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;
public function relations()<br>
{<br>
return array(<br>
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),<br>
);<br>
}
public function relations()<br>
{<br>
return array(<br>
'post' => array(self::BELONGS_TO, 'Post', 'post_id'),<br>
);<br>
}
$dataPosts = Post::model()->with('comments')->findAll();<br>
$dataComments = $dataPosts->comments;
$dataPosts = Post::model()->with('comments')->findByPk(1);
then $dataComments is normally filled with comments. $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
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 questionAsk a Question
731 491 924 answers to any question