Question

In this example, how do you create the "assignments-to-teachers" relationship in the models?

assignments           subjects              teachers
---------             ---------             ------
id                    id                    id
student_id            subject_name          teacher_name
subject_id            teacher_id

I want an SQL query that shows: assignment_id, student_id, subject_name, teacher_name. I used a "belongsTo" to create the "assignments-to-subjects" relationship, but I'm not sure how to create the "assignments-to-teachers".

AssignmentsController.php

public function index() {
    $this->set('assignments', $this->Assignment->find('all'));
}

--------------------------
Assignment.php

public $belongsTo = array(
    'Subject'
);

I did get this to work by adding joins to the "find('all')" in the controller, but I'm wondering how to do this in the models.

AssignmentsController.php 
//(working, but looking to solve this in models, not controller)

$this->set('assignments', $this->Assignment->find('all', array(
        'joins' => array(
            array(
                'table' => 'subjects',
                'alias' => 'Subject',
                'type' => 'LEFT',
                'conditions' => 'Assignment.subject_id = Subject.id'
            ),
            array(
                'table' => 'teachers',
                'alias' => 'Teacher',
                'type' => 'LEFT',
                'conditions' => 'Subject.teacher_id = Teacher.id'
            )
        ),
        'fields' => array('*','Subject.subject_name', 'Teacher.teacher_name')
    )));

No correct solution

OTHER TIPS

As far as I can tell, assignments are related to teachers through subjects, right? Then, on Subject model:

public $belongsTo = array('Teacher');

Also, on AppModel, use Containable behavior:

public $actsAs = array('Containable');

Now, you can do a find on assignment this way:

$this->Assignment->find('all', array(
    'fields' => array('id', 'student_id')
    'contain' => array(
        'Subject' => array(
            'fields' => array('id', 'subject_name')
            'Teacher' => array(
                'fields' => array('id', 'teacher_name')
            )
        )
    )
));

Containable behavior will let you do a deep search through related models

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top