douqu2481 2013-06-06 15:46
浏览 59
已采纳

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?

  • 写回答

2条回答 默认 最新

  • dtmu88600 2013-06-06 15:55
    关注

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

    public function defaultScope()
    {
        return array(
            'with'=> array("images")
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探