2016-04-20 75 views
0

我在蛋糕php.I新想寫兩者之間的連接查詢table.Here我的查詢是:CakePHP的連接查詢不工作

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 

與此查詢運行perfect.But我想寫這個在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); 

這裏這個查詢不執行,所以我該如何解決這個問題?

+0

我可以知道使用的是哪個版本的CakePHP和你想要查詢的地方(例如控制器名稱或型號名稱) –

+0

@MathsRkBala我已經使用CakePHP(tm )v 0.2.9版本。我在控制器中寫了查詢。 –

+0

我可以知道您的控制器名稱(DealPurchasesController或任何其他名稱) –

回答

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 
} 
+0

var $ uses = array( 'DealPurchase' )的意思是什麼? –

+0

將模型(DealPurchase)包含在您的控制器中,您可以訪問(deal_purchases表)中的任何位置(商戶控制器)中的數據。 deal_purchases模型名稱應該是DealPurchase.php –

+0

如何在模型文件中編寫表格的關係? –