我創建數據庫表users
,groups
和group_user
(MySQL的)。而group_user
表(中間表)包含user_id
和role_id
。用戶和小組的關係很多。我想刪除groups
表中的一個組。在刪除組之前,我想檢查是否有任何用戶屬於該組。 我試圖這樣做。如何獲得雄辯從中間表中的數據,硅石
Group.php(型號)
public function users()
{
return $this->belongsToMany('\Modules\User\Models\User');
}
Service.php
public function deleteGroup($data) {
if (!isset($data['groupID']))
return ['error' => 'Failed to delete group. Group id is required'];
$group = Group::find($data['groupID']);
if (!$group)
return ['error' => 'Failed to delete group. Group not found'];
// check any user belongs to group.
$result = $group->users()->pivot->user_id;
if(!$result){
$group->delete();
return ['success' => 'Successfully delete group.'];
}
return ['error' => 'Failed to delete group. Group not found'];
}
但是,這是行不通的。
您應該複製並粘貼錯誤文本而不是(不完整)圖像:-) – mTorres