1

最初,我很快在 CakePHP 中手动编写了一个相当复杂(就结构而言)的 SQL 查询,但现在我试图重写它以使用 CakePHP 的 find 方法运行。

$sql = "SELECT 
    `users`.`username`,
        (SELECT ROUND(SUM(`divisions`.`amount`), 2)
        FROM `purchases` 
        INNER JOIN `divisions` 
        ON `purchases`.`id` = `divisions`.`purchase_id` 
        WHERE `purchases`.`user_id` = `users`.`id` 
        AND `divisions`.`user_id` = `users`.`id`
        AND `purchases`.`group_id` = " . $group_id . " 
    ) AS `owed_to`

    FROM `users` 
    INNER JOIN `memberships` ON `users`.`id` = `memberships`.`user_id` 
    INNER JOIN `groups` ON `memberships`.`group_id` = `groups`.`id`
    WHERE `memberships`.`group_id` =  " . $group_id . "  AND
    `users`.`id` !=  " . $user_id . ";";

因为 SQL 允许您在整个查询中应用 WHERE 过滤器,所以它变得非常简单。在 Cake 你不能只是去:

$results = $this->User->find('all', array(
    'conditions' => array(
        'Membership.group_id =' => $id
    ),...

我试过设置连接:

$joins = array(
    array('table'=>'memberships', 
        'alias' => 'Membership',
        'type'=>'inner',
        'conditions'=> array(
        'Membership.user_id = User.id', 'Membership.group_id' => $id)
    ),

这对于单层递归来说可以,但是与成员资格(例如组)相关的模型不受过滤器的影响。

我只能想象我在做完全错误的事情。

基本上我很困惑,任何帮助将不胜感激。

更多信息

User => HasMany => Purchase, Membership, Division
Membership => BelongsTo => Group, User
Group => HasMany => Membership
Purchase => HasMany => Division
Purchase => BelongsTo => User, Group
Division => BelongsTo => Purchase, User
4

1 回答 1

0

你可以这样写:

$results = $this->User->find('all', array(
  'conditions' => array(
    'Membership.group_id' => $id
),...

如果 User 有很多 Membership 并且 Membership 属于 User,并且 $this->User->recursive = 1,那么它应该可以工作

于 2013-01-15T14:40:25.043 回答