开发者

CakePHP - is there a way of directly querying a HABTM table?

开发者 https://www.devze.com 2023-04-01 17:25 出处:网络
I am trying to check if the Teacher trying to manage a classroom (in the case of my app) is actually in charge of the given classroom. A Teacher habtm Classrooms and viceversa.

I am trying to check if the Teacher trying to manage a classroom (in the case of my app) is actually in charge of the given classroom. A Teacher habtm Classrooms and viceversa.

Is there any way of writing a method in the Teacher model where I supply the user ID and the Classroom ID, and return true or false depending on the Teacher corresponding to the Classroom.

I tried with the following code, but it was giving me a lot of extra information about the models that I don't really need. There has to be a better way:

$this->bindModel(array('hasOne' => array('ClassroomsTea开发者_如何学运维chers')));
    return $this->find('all', array(
            'conditions' => array('ClassroomsTeachers.teacher_id' => $id),
    ));

Thanks


A HABTM relationship is just an abstraction of a hasMany-belongsTo relationship.
Classroom hasMany ClassroomsTeacher belongsTo Teacher.
You can access the joining model like any other model. If the table is classrooms_teachers, the model name is ClassroomsTeacher (singular of ClassroomsTeachers).

$this->Classroom->ClassroomsTeacher->find('count', array(
    'conditions' => array('teacher_id' => $id, 'classroom_id' => $classroomId)
));


The "Cake" way to do this would be as follows:

$this->Classroom->find('first',array(
    'conditions'=>array(
        'Classroom.id'=>$classrom_id_var
    ),
    'recursive'=>1
)

This uses the default recursive flag. I would highly recommend the similar built-in Containable behavoir, so you can do the following:

$classdata = $this->Classroom->find('first',array(
    'conditions'=>array(
        'Classroom.id'=>$classrom_id_var
    ),
    'contain'=>array('Classroom')
)

Either of these will get you an array similar to the following:

array(
    [Classroom] => array(
        ...teacher data...
    ),
    [Teacher] => array(
        [0] => array(
            [id] => 4
            ....
        ),
        [1] => array( ...teacher 2 data... ),
        [2] => array( ...teacher 3 data... ),
    )
)

You could then just run through the Teacher array and make sure the teacher in question is in that array.

For this latter task, you might want to use the useful built-in Set utility - you could do something as follows:

$teacherlist = Set::extract($classdata,'/Classroom/id');
if(in_array($teacherlist, $id)) {
    //They're okay
} else {
    //Return an error
}

If you really want to write it in a model function, look into the join options in find - it's much easier than the bindModel stuff. Or look into the Habtamable behavior.

(Edited to flip around after re-reading question)

0

精彩评论

暂无评论...
验证码 换一张
取 消