1

I have 3 tables: users, specialities, specialities_users.

User HABTM Speciality
Speciality HABTM User
SpecialitiesUser belongsTo Speciality,User

I have also model SpecialitiesUser.

When I want to get specialities for given user I can do it through

SpecialitiesUser->find('all' array('conditions' => array('user_id' => $given_user_id));

Now I want to get all specialities that user NOT belongs to. How I can do this in Cake?

4

1 に答える 1

2

次のコードの$other_specialities変数は、必要なものにする必要があります。

$the_users_specialities = $this->SpecialitiesUser->find('list', array(
    'conditions' => array(
        'SpecialitiesUser.user_id' => $given_user_id
    ),
    'fields' => 'SpecialitiesUser.speciality_id'
));

$other_specialities = $this->Speciality->find('all', array(
    'conditions' => array(
        'NOT' => array(
            'Speciality.id' => $the_users_specialities
        )
    )
));

更新:これは、単一のクエリを使用してそれを行う方法です:

$db = $this->Speciality->getDataSource();

$sub_query = $db->buildStatement(
    array(
        'fields' => array('`SpecialitiesUser`.`speciality_id`'),
        'table' => $db->fullTableName($this->SpecialitiesUser),
        'alias' => 'SpecialitiesUser',
        'conditions' => array('`SpecialitiesUser`.`user_id`' => $given_user_id),
    ),
    $this->Speciality
);

$other_specialities = $this->Speciality->find('all', array(
    'conditions' => array(
        $db->expression('`Speciality`.`id` NOT IN (' . $sub_query . ')')
    )
));
于 2013-02-20T02:48:23.200 に答える