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.
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);
为什么不为courses_user创建模型?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.