如何根据CakePHP中的子结果限制查询结果?

时间:2012-10-31 21:50:42

标签: cakephp cakephp-2.0 conditional-statements

在CakePHP中,如果我运行以下查找命令

$this->Instructor->find('all');

返回以下内容:

Array
(
    [0] => Array
        (
            [Instructor] => Array
                (
                    [id] => 1
                    [user_id] => 3
                    [bio] => A billionaire playboy, industrialist and ingenious engineer, Tony Stark suffers a severe chest injury during a kidnapping in which his captors attempt to force him to build a weapon of mass destruction. He instead creates a powered suit of armor to save his life and escape captivity. He later uses the suit to protect the world as Iron Man.
                )

            [User] => Array
                (
                    [id] => 3
                    [first_name] => Tony
                    [last_name] => Stark
                    [asurite_user] => tstark
                    [asurite_id] => 
                    [password] => 
                    [email] => tstark@example.com
                    [created] => 2012-10-30 09:57:36
                    [modified] => 2012-10-30 09:57:36
                )

            [Course] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [slug] => beatles
                            [sln] => AAA001
                            [course_number] => 
                            [title] => The Beatles
                            [description] => This is a class about the Beatles.  If this were a real description, more information would be listed here.
                            [state] => 
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [slug] => elvis
                            [sln] => AAA002
                            [course_number] => 
                            [title] => Elvis: The King of Rock
                            [description] => All about the king of rock and roll, Elvis Presley.
                            [state] => 
                        )

                )

        )

    [1] => Array
        (
            ...

“教练”和“课程”之间存在多对多的关系。如何根据每个“讲师”所属的“课程”过滤结果?我尝试了以下但没有成功:

$instructors = $this->Instructor->find('all', array(
    'conditions' => array('Course.id' = 2)
));

2 个答案:

答案 0 :(得分:1)

如果您尝试根据针对子项的条件限制父项,则可以通过子模型而不是主模型进行主查询,然后使用contain()其余部分,或使用MySQL加入 - 通过joins()在CakePHP中提供。

答案 1 :(得分:0)

您需要(重新)使用hasOne绑定Instructor模型的关联并使用以下设置:

'CoursesInstructor' => array(
    'className' => 'CoursesInstructor',
    'foreignKey' => false,
    'conditions' => 'Instructor.id = CoursesInstructor.id'),
'Course' => array(
    'className' => 'Course',
    'foreignKey' => false,
    'conditions' => 'CoursesInstructor.course_id = Course.id');

这将生成具有所需连接的正确SQL,并且您的条件将起作用。