gpt4 book ai didi

php - cakephp 加入查询不起作用

转载 作者:行者123 更新时间:2023-11-29 21:06:54 27 4
gpt4 key购买 nike

我是 cake 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);

此处未执行此查询,那么我该如何解决此问题?

最佳答案

请检查您的文件的以下内容:

您的 Controller 顶部“$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
}

关于php - cakephp 加入查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36739922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com