php – 如何从eloquent,silex中的中间表中获取数据

前端之家收集整理的这篇文章主要介绍了php – 如何从eloquent,silex中的中间表中获取数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我创建了数据库表users,groups和group_user(MySQL).而group_user表(中间表)包含user_id和role_id.用户和群体的关系是多对多的.我想删除组表中的组.在删除组之前,我想检查是否有任何用户属于该组.
我试着这样做.

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

我就是这样做的.如果还有其他方式请告诉我.谢谢.

猜你在找的MySQL相关文章