1

如何在 cakePHP 1.3 上创建此查询

 SELECT "Redeem_log"."benefit_id", count("Redeem_log"."benefit_id") as JUMLAH FROM  "redeem_logs" "Redeem_log" 
LEFT JOIN "benefits" "Benefit" ON ("Redeem_log"."benefit_id" = "Benefit"."id") 
LEFT JOIN "merchants" "Merchant" ON ("Benefit"."merchant_id" = "Merchant"."id")  
LEFT JOIN "merchant_types" "Merchant_type" ON ("Merchant"."merchant_type_id" = "Merchant_type"."id") 
WHERE "Redeem_log"."benefit_id" IS NOT NULL AND ("Merchant_type"."merchant_type"='lokal' OR "Merchant_type"."merchant_type"='nasional') GROUP BY "Redeem_log"."benefit_id"  ORDER BY "JUMLAH" DESC  

我不想使用 belongsTO、hasMany 或 ect
如果我使用

var $belongsTo = array(
    'Benefit' => array('className' => 'Benefit',     'foreignKey' => 'benefit_id'),
    'Merchant' => array('className' => 'Merchant', 'foreignKey' => 'merchant_id')
);

左连接就像:

SELECT "Redeem_log"."benefit_id", count("Redeem_log"."benefit_id") as JUMLAH 
FROM "redeem_logs" "Redeem_log" 
LEFT JOIN "benefits" "Benefit" ON ("Redeem_log"."benefit_id" = "Benefit"."id") 
LEFT JOIN "merchants" "Merchant" ON ("Redeem_log"."merchant_id" = "Merchant"."id") 
WHERE "Redeem_log"."benefit_id" IS NOT NULL  GROUP BY "Redeem_log"."benefit_id"  
ORDER BY "JUMLAH" DESC  
4

2 回答 2

0

在 MOdel::find() 的 params 参数中添加 joins 字段;

像这样

$params = array(
    'joins'=>array(
         array(
             'table'=>'users',
             'alias'=>'User',
             'type'=>'LEFT/RIGHT/INNER',
             'conditions'=>array("$this->Alias.foreignKey=User.pk")
         )
     )
);
于 2013-09-27T06:19:15.367 回答
0

我会这样做,查询的参数看起来有点吓人,但是当你仔细查看它时,它是有道理的:

$params = array(
    'recursive' => -1,
    'fields' => array('RedeemLog.benefit_id', 'COUNT(RedeemLog.benefit_id) as JUMLAH'),
    'conditions' => array(
        array('NOT' => array('RedeemLog.benefit_id' => null)),
        array('Merchanttype.merchant_type' => array('lokal', 'nasional')),
     ),
     'joins' => array(
         array(
             'table' => 'benefits',
             'alias' => 'Benefit',
             'type' => 'LEFT',
             'conditions' => array('RedeemLog.benefit_id = Benefit.id')
         ),
         array(
            'table' => 'merchants',
            'alias' => 'Merchant',
            'type' => 'LEFT',
            'conditions' => array('Benefit.merchant_id = Merchant.id')
         ),
         array(
            'table' => 'merchant_types',
            'alias' => 'Merchanttype',
            'type' => 'LEFT',
            'conditions' => array('Merchant.merchant_type_id = Merchanttype.id')
         ),
     ),
     'order' => 'JUMLAH DESC',
     'group' => 'RedeemLog.benefit_id',
 );

最后找到蛋糕

 $result = $this->RedeemLog->find('all', $params);

希望对你有效。

于 2013-03-07T15:01:03.397 回答