0

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

$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
        (
            ...

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

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

2 回答 2

1

如果您尝试根据子项的条件限制您的父项,您可以通过子模型而不是主模型进行主查询,并包含()其余部分,或者使用 MySQL Joins - 在 CakePHP 中可用通过joins()

于 2012-11-01T04:04:16.483 回答
0

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

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

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

于 2012-10-31T22:15:03.177 回答