Yii使用另一种模型关系加入表

Let says we have three tables, Posts, Users and Images. Where the post has a relation to the users table and the images has a relation to the user table, so that a post belongs to a user and an image belongs to a user.

Post {
    post_id
    user_id
}

Users {
     user_id
}

Images {
    image_id
    user_id
}

Now in Yii, the relations can be defined in the model. I have the relations set up like so:

<?php

class Users extends CModel {
    public function relations() {
      'images' => array(self::HAS_ONE, 'Images', 'user_id')
      'posts' => array(self::HAS_MANY, 'Posts', 'user_id')
    }
}

class Images extends CModel {
    public function relations() {
      'user' => array(self::HAS_ONE, 'Users', 'user_id')
    }
}

class Posts extends CModel {
    public function relations() {
      'user' => array(self::HAS_ONE, 'Users', 'user_id')
    }
}

Now in Yii, using the DBCriteria I can query for this using CDbCriteria with the 'with' function. My question is how can query on the Post Model, and use the the relationship inside the Users model to get the users image?

Example:

CActiveDataProvider('Posts', array(
            'criteria'=>array(
                'with' => array('users', 'Users.images'),
            ),
            'pagination'=>array(
                'pageSize'=>20,
            ),
        ));

Is there a way of accomplishing this in Yii?

You could use defaultScope in Users model to make it always join to images model:

public function defaultScope()
{
    return array(
        'with'=> array("images")
    );
}

I think this might be a 'Doh...' moment for you, but the relation to the Users model from the Posts model is named user not users. The with() function refers to the relation not the model.