删除关联记录 - cakephp 3

Deleting records with associations - cakephp 3

我是 cakephp 3 的新手,我真的不知道该怎么做。

我有一个组table和一个用户table,他们有一个组有很多用户的关系。

我想做的是,如果我想删除一个组,并且说该组有任何用户,那么它就不能删除。群组为空才能删除

我一周前才开始使用 cakephp,对此我很迷茫,所以我非常感谢你能给我的任何帮助。

您可以计算一个组中的用户数,如果为 0 则删除它,如果不是则不删除

use Cake\ORM\TableRegistry;
$users = TableRegistry::get('Users'); //or simply use $this->loadModal('Users');

//asuming the Users table has a group_id to identify the group
$query = $users->findByGroupId('id_of_the_group_you_wanna_delete')->count();
    if ($query === 0) {
        //delete group
    } else {
        //show warning not able to delete group
    }

一定要查看 ndm 下面关于事务的评论and/or 外键约束