如何从 table in eloquent 的中间获取数据,silex

How to get data from intermediate table in eloquent, silex

我创建了数据库 tables usersgroupsgroup_user (MySQL)。并且 group_user table(中间table)包含user_idrole_id。用户和组的关系是多对多的。我想删除 groups table 中的一个组。在删除组之前,我想检查是否有任何用户属于该组。 我试过这样做。

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'];
}

但这行不通。

我找到了。

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

我就是这样做的。如果有其他方法请告诉我。谢谢