Cycs
Cycs

Reputation: 239

Laravel many-to-many relationships

I am trying to work with many to many relationships in my web application. I have a table called groups and table called users.

Many users can be in many groups and many groups can have many users. i.e there can be an infinate amount of users and groups, and users can belong to as many groups as they wish.

I have created a pivot table successful, and my models, look like this.

User.php

<?php

class User extends \Eloquent {

protected $fillable = [];

protected $table = 'user';

public function groups()
{
    return $this->belongsToMany('Group');
}

}

Group.php

class Group extends \Eloquent {

protected $fillable = [];

public function users()
{
    return $this->belongsToMany('User');
}

}

I am trying to get to grips with Eloquent ORM and I am doing the following,

public function get($id)
{

    //dd(Activity::log());
    $group = Group::find($id);

    return $group->users;

}

This returns a results that looks like this,

[
{
    "id": "1",
    "firstname": "User",
    "surname": "One",
    "email": "[email protected]",
    "password": "password",
    "remember_token": null,
    "created_at": "-0001-11-30 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "pivot": {
        "group_id": "1",
        "user_id": "1"
    }
},
{
    "id": "2",
    "firstname": "User",
    "surname": "Two",
    "email": "[email protected]",
    "password": "password",
    "remember_token": null,
    "created_at": "-0001-11-30 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "pivot": {
        "group_id": "1",
        "user_id": "2"
    }
}

]

This is not exactly what I was looking for, I was hoping that I would get something more explicit, meaning a rows returned including the group name etc, and the user details.

To get the group details I can switch the query in the get() function around, and then the pivot object in the returned results becomes the user details. To then get the user data do I need run further queries on that data.

Essentially what I hoping to output in the long run is,

Group Name 1
---------------------------------
Members
---------------------------------
    User One
    User Two
    User Five
    User Six
    User Ten
    User Nineteen

Upvotes: 0

Views: 871

Answers (1)

Benubird
Benubird

Reputation: 19547

Sounds like you want an object consisting of on model, attached to its relations - called "eager loading" in laravel. There is a syntax for that:

Group::find($id)->with('users')->first() //or
Group::with('users')->get() //etc.

See more details here: http://laravel.com/docs/eloquent#eager-loading

Upvotes: 3

Related Questions