cakephp join查询无法正常工作

时间:2016-04-20 09:46:45

标签: php mysql cakephp

我是蛋糕php的新手。我想在两个表之间编写连接查询。我的查询是:

select * from deal_purchases as dp 
  join users as u on u.id = dp.user_id
  where dp.deal_id = 6
  group by user_id

并且此查询运行完美。但我想在cakephp中编写此查询。我写过这样的查询:

$table = "deal_purchases";
$query['conditions'] = array('deal_purchases.deal_id'=>$deal_id);
$query['fields'] = array('deal_purchases.*','users.*');
$query['joins'] = array(
                    array(
                        'table'=>'users',
                        'alias'=>'users',
                        'type'=>'INNER',
                        'conditions'=>array('users.id = deal_purchases.user_id')
                        ),
                );
$query['group'] = array('deal_purchases.user_id');
$result = $this->find('all', $query);

此处此查询未执行,因此如何解决此问题?

1 个答案:

答案 0 :(得分:0)

请检查以下文件:

您的控制器顶部" $uses"数组包含" DealPurchase" 实施例

class MerchantController extends AppController {
    var $uses = array(
        'DealPurchase'
    );

尝试以下

$query['conditions'] = array('DealPurchase.deal_id'=>$deal_id);
$query['fields'] = array('DealPurchase.*','User.*');
$query['joins'] = array(
                    array(
                        'table'=>'users',
                        'alias'=>'User',
                        'type'=>'INNER',
                        'conditions'=>array('User.id = DealPurchase.user_id')
                        ),
                );
$query['group'] = array('DealPurchase.user_id');
$result = $this->DealPurchase->find('all', $query);

数据库表deal_purchases 对于型号名称应为DealPurchase.php,格式如下

<?php 
class DealPurchase extends AppModel {
    var $name = "DealPurchase";
    //Relationship some tables
    //Validation here
}
?>

User.php模型(用户)

class User extends AppModel {
    var $name = "User"; 
    var $hasMany = array(
        'DealPurchase' => array(
            'className' => 'DealPurchase',
            'foreignKey' => 'user_id',
            'dependent' => true //true means when delete the user entry via coding then also deleted the deal_purchases entry also
        )
    );
    //validation
}

DealPurchase.php模型(deal_purchases)

class DealPurchase extends AppModel {
    var $name = "DealPurchase"; 
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );
    //validation
}