我创建了数据库表users
,groups
和group_user
(MySQL)。而group_user
表(中间表)包含user_id
和{{ 1}}。用户和群体的关系是多对多的。我想删除role_id
表中的一个组。在删除组之前,我想检查是否有任何用户属于该组。
我试着这样做。
Group.php(Model)
groups
Service.php
public function users()
{
return $this->belongsToMany('\Modules\User\Models\User');
}
但这不起作用。
答案 0 :(得分:3)
我发现了。
service.php
public function deleteGroup($data) {
$group = Group::find($data['groupID']);
if (!$group){
return [
"msg" => "Failed to delete group. Group not found."
];
}
// find out any one belongs to the group.
$result = $group->users->first()->userID;
if ($result){
return [
"msg" => "Failed to delete group. Group has users."
];
}
$result = $group->delete($data['groupID']);
if(!$result){
return [
"msg" => "Failed to delete group."
];
}
return [
"msg" => "Successfully deleted group."
];
}
我就是这样做的。如果还有其他方式请告诉我。感谢。