开发者

is this a really bad way to do queries across multiple HABTM models?

I am trying to query across two HABTM tables. I have Leases Managers Tenants Properties.

Managers HABTM Tenants

Managers HABTM Properties

Tenants HABTM Leases

What I want to do is find a list of Properties linked to Managers linked to开发者_Go百科 Tenant. I have been able to accomplish the query with the code below BUT I am only able to retrieve Property_id (from the Managers_Property model) and not Property.name (from the Property model).

I get the nagging feeling I am doing something very wrong or unnecessary here but I've been banging my head against the wall and haven't been able to figure this out.

    $conditionsSubQuery['`ManagersTenant`.`tenant_id`'] = $this->Auth->User('id');
        $dbo = $this->Lease->getDataSource();
        $subQuery = $dbo->buildStatement(
            // SELECT `ManagersTenant`.`manager_id` FROM `managers_tenants` AS `ManagersTenant`   WHERE `ManagersTenant`.`tenant_id` = $this->Auth->User('id')
            array(
                'fields' => array('`ManagersTenant`.`manager_id`'),
                'table' => $dbo->fullTableName($this->Lease->LeasesManager->Manager->ManagersTenant),
                //'table' => $dbo->fullTableName($this->Lease->Property->ManagersProperty->Manager->ManagersTenant),
                'alias' => 'ManagersTenant',
                'limit' => null,
                'offset' => null,
                'joins' => array(),
                'conditions' => $conditionsSubQuery,
                'order' => null,
                'group' => null
            ),
            $this->Lease->LeasesManager->Manager->ManagersTenant
            //$this->Lease->Property->ManagersProperty->Manager->ManagersTenant
        );
        $subQuery = ' `ManagersProperty`.`manager_id` IN (' . $subQuery . ') ';
        $subQueryExpression = $dbo->expression($subQuery);
        $conditions[] = $subQueryExpression;
        $properties = $this->Lease->Property->ManagersProperty->find('list', array(
            'conditions' => $conditions,
            'fields' => array('property_id',),
            'recursive' => 3
            )
        );

Any help is much appreciated.


Seems like you should be using the Containable behavior: http://book.cakephp.org/view/1323/Containable

$contain = array(
    'Manager' => array(
        'Property'
    )
);
$conditions = array('Tenant.id' => $this->Auth->user('id'));
$tenants = $this->Tenant->find('first', array('conditions'=>$conditions, 'contain'=>$contain));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜