Tim
Tim

Reputation: 13258

CakePHP - HABTM - get results of joined database table

I am using CakePHP 2.0 and I have a many-to-many relationship betweens users and courses. I have a database table users, courses and courses_users.

The problem is deleting courses which are already associated with a user. I won't delete them if there is an association to a user in courses_users.

So I wrote in my model Course.php

function beforeDelete() {
    if (??? == 0) {
        return true;
    }
    return false;
}

What I need is a database query written in CakePHP, so that I can determine if a course is not associated to any user (x == 0). How can I do this? With a 1:n relationship I can write this

if($this->User->find("count", array("conditions" => array("course_id" => $this->id))) == 0)

but how can I do this in my n:m relationship?

Best Regards.

Upvotes: 1

Views: 713

Answers (2)

Lucian Vasile
Lucian Vasile

Reputation: 502

You can check the same as you would for hasMany, because one Course hasMany User and one User hasMany Course.

So try this (you won't need to create the UsersCourse or CoursesUser model)

In the Course model:

public $hasAndBelongsToMany = array('User');

//in your method

if($this->CoursesUser->find("count", array("conditions" => array("course_id" => $this->id))) == 0);

Upvotes: 1

Shahruk Khan
Shahruk Khan

Reputation: 1

Why not create a model for courses_user?

Upvotes: 0

Related Questions