2016-01-23 52 views
5

我創建數據庫表usersgroupsgroup_user(MySQL的)。而group_user表(中間表)包含user_idrole_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']; 
} 

但是,這是行不通的。

+1

您應該複製並粘貼錯誤文本而不是(不完整)圖像:-) – mTorres

回答

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." 
    ]; 
} 

這是我要做的事。如果有另一種方式,請告訴我。謝謝。

+2

也可以這樣做。 $ result = $ group-> users-> count(); if($ result> 0){ return $ this-> response(true,$ errMsg。'Group has users'); } else { $ group-> delete($ data ['groupID']); return $ this-> response(false,'Group deleted successfully'); }' –