1

したがって、私のモデルの関連付けは次のとおりです。

人は多くの賞を持っています

個人の列:id、名前賞の列:id、person_id、名前

そのため、多くの賞を受賞することができますが、同時に2つの異なる賞を受賞している特定の人だけを取得したいと思います。findメソッドでこれを実現する方法はありますか?

4

2 に答える 2

0

Have a look at subqueries at the end of the page. You basically need a subquery because you need to query the Award table twice to match value1 and value2.


Edit : Example code

$conditionsSubQuery['`Award`.`name`'] = 'value2';
$dbo = $this->Person->getDataSource();
$subQuery = $dbo->buildStatement(
    array(
        'fields' => array( '`Person2`.`id`'),
        'table' => $dbo->fullTableName($this->Person),
        'alias' => 'Person2',
        'limit' => null,
        'offset' => null,
        'joins' => array(),
        'conditions' => $conditionsSubQuery,
        'order' => null,
        'group' => null
    ),
    $this->Person
);
$subQuery = ' `Person`.`id` IN (' . $subQuery . ') ';
$subQueryExpression = $dbo->expression($subQuery);
$conditions[] = array('Award.name' => 'value1');
$conditions[] = $subQueryExpression;
$this->Person->find('all', compact('conditions'));

I haven't tested it and it might not work, but you got the idea.


Edit 2: To answer your comment

So basically what you want as an SQL result is

select 
    users.id 
from 
    users 
left join 
    awards 
where 
    awards.name in ('award1', 'award2', 'award3', 'award4') 
group by 
    awards.name 
having 
    count(awards.name) = 4

To achieve that you may do it that way :

$awards = array('award1', 'award2', 'award3', 'award4');

$this->Person->find(
    'all',
    array(
        'joins' => array(
            array(
               'table' =>'awards',
               'alias' => 'Award',
               'type' => 'LEFT',
               'conditions' => 'Award.person_id = person.id'
             )
        ),
        'conditions' => array(
            'Award.name' => $awards,
        ),
        'group' => array('Award.name HAVING '.count($awards))
    )
);
于 2012-05-16T15:59:58.427 に答える
0
$persons = $this->Person->find('all', array(
                           'recursive' => -1,
                           'conditions' => array(
                              'AND' => array('Award.name' => 'Award 1', 'Award.name' => 'Award 3')
                            ),
                           'joins' => array(
                                array(
                                   'table' =>'awards',
                                   'alias' => 'Award',
                                   'type' => 'LEFT',
                                   'conditions' => 'Award.person_id = person.id'
                                 )
                            )
                      )
                 );
于 2012-05-16T16:27:34.123 に答える