5

I am currently trying to make a relation between 3 tables.

Users
    uid
    username
Groups
    gid
    groupname
GroupMembers
    uid
    gid

With eloquent ORM, how do I get the Groups of a User?
With just 1 line of query I wanted to return a json reply like: (search group that I am a member of... keyword: Admin)

Status 200
User   uid 1
       username mrwootwoot

       Groups
            {
             gid 1
             groupname administrators
            }
            {
             gid 2
             groupname wadmin
            }

What I got so far is:

$joined_networks = User::whereHas('groups', function($q)
{
    $q->where('is_blocked', '=', 0)->where('name','like',"%admin%");
})->with('groups')->where('uid', $user_id)->get();

(...)

return Response::json(array(
    'status' => 200,
    'user' => $joined_networks->toArray()
));

This part of the code is suppose to find the groups the user is a member of where he is not blocked.


update

$joined = User::with('group')->where('uid', $user_id)->get();

return Response::json(array(
    'status' => 200,
    'results' => $joined
));

and my user model:

public function group()
{
    return $this->hasManyThrough('Group', 'GroupMembers', 'uid', 'gid');
}

Now it just returns nothing

{
    "status": 200,
    "results": {

    }
}

update

$user = User::find($user_id);
$user_groups = $user->groups();

return Response::json(array(
    'status' => 200,
    'results' => $user_groups
));

But still the same as above, no result being given back.


update It was a mistake on the output. $user_groups->toArray() is the right one. Works well now.

madziikoy
  • 1,447
  • 7
  • 22
  • 32

1 Answers1

8

How about something like this?

in the user model put

public function groups()
{
return $this->hasManyThrough('groups', 'GroupMembers', 'uid', 'id');
}

in the groups model put (not sure if this is necessary

public function users()
{
return $this->hasMany('GroupMembers', 'gid', 'id);
}

and then to get groups use

return $this->user->groups

I got this from the laravel docs here http://laravel.com/docs/eloquent#has-many-through

Mark
  • 3,137
  • 4
  • 39
  • 76
  • Above solution is not the best solution for actual Eloquent Relationships. Please follow the docs: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many – Diptesh Atha Mar 16 '17 at 09:14