0

假设查询有效:

SELECT
    users.id,
    subscriptions.name,
    users.user_type
FROM users
LEFT JOIN users_subscriptions
    ON users.id = users_subscriptions.user_id
LEFT JOIN subscriptions
    ON users_subscriptions.subscription_id = subscriptions.id
WHERE
    subscriptions.name = 'advertisers'
    AND
    users.user_type = 'agent';

如何使用 cakePHP 1.3 在单个查询中执行此操作?

编辑:加入是正确的方法吗?

4

2 回答 2

1

是的,加入就好了。只需确保在搜索到您的 User 模型 a hasOnetoUsersSubscriptionUsersSubscription作为 belongsTo 的模型之前即时添加Subscription。然后使用可包含的行为来包含'UserSubscription' => 'Susbcription'

您的代码可能如下所示:

$this->User->bindModel(array('hasOne' => array('UserSubscription')));
$this->User->UserSubscription->bindModel(array('belongsTo' => array('Subscription')));
$results = $this->User->find('all', array(
    'contain' => array(
        'UserSubscription' => 'Subscription'
    )
));
于 2013-05-22T11:26:01.073 回答
1

您可以像这样以“CakePHP 方式”设置查询:

$conditions = array(
    'Subscriptions.name' => 'advertisers',
    'Users.user_type'    => 'agent'
);

$joins = array(
    array(
        'table'      => 'users_subscriptions',
        'alias'      => 'UsersSubscriptions',
        'type'       => 'LEFT',
        'conditions' => array(
            'UsersSubscriptions.user_id=Users.id'
        )
    ),
    array(
        'table'      => 'subscriptions',
        'alias'      => 'Subscriptions',
        'type'       => 'LEFT',
        'conditions' => array(
            'Subscriptions.id=UsersSubscriptions.subscription_id'
        )
    )
);
$fields = array(
    'Users.id', 'Users.user_type', 'Subscriptions.name'
);

$options = array(
    'conditions' => $conditions,
    'joins'      => $joins,
    'fields'     => $fields
);

$results = $this->Users->find('all', $options);
于 2013-05-22T14:09:37.900 回答