CakePHP - HABTM - 获取连接数据库表的结果
我正在使用 CakePHP 2.0,并且用户和课程之间存在多对多关系。 我有一个数据库表users
、courses
和courses_users
。
问题是删除已经与用户关联的课程。如果 courses_users
中存在与用户的关联,我不会删除它们。
所以我在我的模型中编写了 Course.php
function beforeDelete() {
if (??? == 0) {
return true;
}
return false;
}
我需要的是用 CakePHP 编写的数据库查询,以便我可以确定课程是否未与任何用户关联(x == 0)。 我该怎么做?对于 1:n 关系,我可以这样写
if($this->User->find("count", array("conditions" => array("course_id" => $this->id))) == 0)
,但是如何在 n:m 关系中做到这一点?
此致。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像检查 hasMany 一样检查,因为一门课程有很多用户,而一个用户有很多课程。
因此,尝试这个(您不需要创建 UsersCourse 或 CoursesUser 模型)
在 Course 模型中:
// 在您的方法中
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:
//in your method
为什么不为 course_user 创建一个模型?
Why not create a model for courses_user?