Trying to get property of non-object, 无法访问关联对象属性

Post 与 Post_Description共享主键:

Post:

public function relations(){

return array(

'description'=>array(self::HAS_MANY, 'Post_Description', 'post_id'),

);

}

Post_Description:

public function relations() {

return array(

 'post'=>array(self::BELONGS_TO, 'Post', 'post_id'),

);

}

单元测试

$post = Post::model()->findByPk(18);

$this->assertNotNull($post->descriotion);

$this->assertEquals($post->description->name, "name"); <------Trying to get property of non-object

望各位指点。 :rolleyes:

是不是这个关联对象是空的? 如果访问空对象的属性 就会有这样的错误。 需要先加个判断。

yiic 去执行时候因为调用另外一个model 所以可能会出现Trying to get property of non-object

所以在要在调用model之前判断这个model是否存在

解决方案:

http://yxmhero1989.blog.163.com/blog/static/112157956201171883740729/