如何使用Yii ActiveRecord关系?

时间:2015-05-04 09:51:17

标签: php activerecord yii

我怎么能像这个sql一样搜索

select user.user_id,count(distinct user.user_id,user_lesson_read.lesson_id) as counter 
FROM 
user 
inner join 
user_lesson_read 
ON (user.user_id =user_lesson_read.user_id)
GROUP BY user_lesson_read.user_id
having counter >=3

在ARs? 这是db结构:

User
--------------------
user_id     |
1           |
--------------------

LessonRead
-------------------------------------
user_id |   lesson_id   | section_id
-------------------------------------
1       |   2           |   A
-------------------------------------
1       |   2           |   B
-------------------------------------
1       |   3           |   A
-------------------------------------
1       |   4           |   A
-------------------------------------

用户1有3个课程记录(课程2,3,4)
我试过像

这样的东西
'userLessonRead'=>array(
            'select'=>'count(distinct t.user_id,t.lesson_id) as b',
            //'condition'=>'',
        ),

我将得到一个CDbException,并且sql不正确:

t.lesson_id) as b, // one parenthesis here

任何人都有帮助吗?谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个,

  

在用户模型中,

public function relations()
{

        return array(
                    "lessonread"  => array(self::HAS_MANY,"LessonRead","user_id")
        );
}

在搜索()中,

$criteria->with = array("user_lesson_read")
$criteria->group = 'user_lesson_read.user_id';
$criteria->having = 'count(distinct t.user_id,t.lesson_id) > 3';
  

在LessonRead模型中,

public function relations()
{

        return array(
                    "user"  => array(self::BELONGS_TO,"User","user_id")
        );
}