2

我的应用程序的数据模型

  • 组有很多用户
  • 用户属于组
  • 用户 hasMany Punch
  • 打孔属于用户
  • 打卡属于PayPeriod
  • PayPeriod hasMany Punch

找电话

$groups = $this->Group->find('all', array( 'contain' => array(
    'User' => array(
        'Punch' => array(
            'conditions' => array(
                'Punch.payperiod_id' => null
            )
        )
    )

)));

查询调试

SELECT `Group`.`id`, `Group`.`name` 
FROM `pclock`.`groups` AS `Group` 
WHERE 1 = 1 ORDER BY `name` ASC

SELECT `User`.`id`, `User`.`name`, `User`.`group_id` 
FROM `pclock`.`users` AS `User` 
WHERE `User`.`group_id` IN (4, 3, 5, 2, 1)

SELECT `Punch`.`id`, `Punch`.`user_id`, `Punch`.`time_in`, `Punch`.`time_out`, `Punch`.`payperiod_id` 
FROM `pclock`.`punches` AS `Punch` 
WHERE `Punch`.`payperiod_id` IS NULL AND `Punch`.`user_id` IN (1, 2, 3, 4, 5)

一旦我的应用程序扩展到数百个用户,每个用户都有数千个 Punches,这些查询可能会变得非常低效。我希望 Containable 执行以下查询:

查询我更喜欢

SELECT 
    Group.id, Group.name, 
    User.id, User.name, User.group_id, 
    Punch.id, Punch.user_id, Punch.time_in, Punch.time_out, Punch.payperiod_id 
FROM groups AS Group
LEFT JOIN users AS User 
    ON (Group.id = User.group_id)
LEFT JOIN punches AS Punch 
    ON (User.id = Punch.user_id)
WHERE Punch.payperiod_id IS NULL

有没有办法优化这个?options 数组中的 join 属性似乎被忽略了,并且在没有 Containable 的情况下手动执行连接会返回非分层的结果。

4

2 回答 2

2

您可以手动加入:

$groups = $this->Group->find('all', array(
    'fields'=>array(
        'Group.id', 'Group.name', 'User.id', 'User.name', 'User.group_id', 
        'Punch.id', 'Punch.user_id', 'Punch.time_in', 'Punch.time_out',
        'Punch.payperiod_id'
    ),
    'conditions'=>array(
        'Punch.payperiod_id IS NULL'
    ),
    'joins'=>array
        array(
           'table'=>'users',
           'alias'=>'User',
           'conditions'=>array(
               'Group.id = User.group_id'
           )
        ),
        array(
            'table'=>'punches',
            'alias'=>'Punch',
            'conditions'=>array(
                'User.id = Punch.user_id'
            )
        )
    )
));
于 2012-05-10T16:13:29.577 回答
2

这就是可包含的工作方式。您可以在查找中使用连接参数或查找为您执行连接的可链接行为。

https://github.com/rafaelbandeira3/linkable

于 2012-05-09T22:34:38.737 回答