查询连接三个表yii

时间:2012-09-24 06:18:24

标签: php mysql yii

如何将mysql查询转换为yii。?

我有3张桌子

  1. user_header
  2. 客户
  3. customer_ratings
  4. 这是我的SQL查询

    SELECT t.email 
    FROM   otz_user_header t 
           JOIN otz_customers r 
             ON t.user_id = r.customer_user_id 
           JOIN otz_customer_ratings cr 
             ON cr.customer_user_id = r.customer_user_id 
    WHERE  r.rate_auto_approve = 0 
           AND r.rate_email_time IS NOT NULL 
           AND r.total_rating_count IS NOT NULL 
           AND cr.rating_date < Curdate() 
           AND cr.rating_date > Date_sub(Curdate(), INTERVAL 7 day) 
    

    如何将此查询转换为yii?

    提前致谢。

2 个答案:

答案 0 :(得分:10)

&#34;鼬&#34;回答是正确的,但如果你正在寻找积极的记录......

型号: UserHeader

关系:

'activeCustomers' => array(
     self::HAS_MANY, 
     'Customer', 
     'customer_user_id', 
     'condition' => 'activeCustomers.rate_auto_approve=0 
                  AND activeCustomers.rate_email_time IS NOT NULL 
                  AND activeCustomers.total_rating_count IS NOT NULL'
),

型号:客户

关系:

'lastWeekRatings' => array(
     self::HAS_MANY, 
     'CustomerRating', 
     'customer_user_id', 
     'condition' => 'lastWeekRatings.rating_date < CURDATE() 
        AND lastWeekRatings.rating_date > DATE_SUB( CURDATE(), INTERVAL 7 DAY )'
),

以下代码返回与查询相同的MODEL对象。 (我还没有测试过它)

$useremails = UserHeader::model()
     ->with('activeCustomers', 'activeCustomers.lastWeekRatings')
     ->findAll(array(
           'select' => 't.email'
      ));
print_r($useremails);

答案 1 :(得分:5)

使用DAO(数据访问对象

<强> MODEL


public function test(){
        $sql = "SELECT t.email
            FROM otz_user_header t
            JOIN otz_customers r ON t.user_id = r.customer_user_id
            JOIN otz_customer_ratings cr ON cr.customer_user_id = r.customer_user_id
            WHERE r.rate_auto_approve =0
            AND r.rate_email_time IS NOT NULL
            AND r.total_rating_count IS NOT NULL
            AND cr.rating_date < CURDATE( )
            AND cr.rating_date >DATE_SUB( CURDATE( ) , INTERVAL 7
            DAY )";

        return Yii::app()->db->createCommand($sql)->queryAll();
            }