CakePHP - HABTM - 获取连接数据库表的结果

发布于 2025-01-04 14:52:02 字数 614 浏览 3 评论 0原文

我正在使用 CakePHP 2.0,并且用户和课程之间存在多对多关系。 我有一个数据库表userscoursescourses_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

背叛残局 2025-01-11 14:52:02

您可以像检查 hasMany 一样检查,因为一门课程有很多用户,而一个用户有很多课程。

因此,尝试这个(您不需要创建 UsersCourse 或 CoursesUser 模型)

在 Course 模型中:

public $hasAndBelongsToMany = array('User');

// 在您的方法中

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

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);
违心° 2025-01-11 14:52:02

为什么不为 course_user 创建一个模型?

Why not create a model for courses_user?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文