这样的关联如何实现 eager loading

Post 模型:

id, owner_id, content

PostComment 模型

id, owner_id, post_id, content

Post 关联

‘comments’ => array(self::HAS_MANY, ‘PostComment’, ‘post_id’)

‘owner’ => array(self::BELONGS_TO, ‘Member’, ‘owner_id’),

PostComment 关联

‘owner’ => array(self::BELONGS_TO, ‘Member’, ‘owner_id’),

我的需求:

查询指定的 Post 的时候,一起查询出 Post 的 owner 数据以及所有 comments 和他的 Owner 数据。

现在我使用如下语句:

Post::model()->with(array(‘owner’, ‘comments’))->findByPk(1);

这样将产生 1 + comments 条 SQL 语句

我想一次性查询出 Post 的 owner 和 Comment 的 owner 数据。

尝试了一下,没有成功。不知这样的需求如何处理,指教一下。多谢。

你这样做应该没有问题,请打开调试信息看下

$model=Post::model()->with(array(‘owner’, ‘comments’))->findByPk(1);

print_r($model);

嗯。这样是没有问题,但是我想一起取出 comment 的 owner 信息就有问题了。应该是关联重名的问题。因为post 和 postcomment 都有一个关联是 owner。

顶顶。(:slight_smile:)