user4877203
user4877203

Reputation: 57

Laravel eager loading with field limit

I have three tables:

users

role_user

roles

Now I want to get a user list with users.id,users.name, roles.id. That's my code:

    $query = User::with(['roles'=>function($q){
        $q->lists('role_id');
    }])->get(['id','name']);

the response like that

       {
            "id": "1",
            "name": "aaaa",
            "roles": []
        },
        {
            "id": "2",
            "name": "bbbb",
            "roles": []
        },

when i don't pass the array to get method,the response like that:

     {
            "id": 1,
            "name": "aaaa",
            "password": "xxxxxxx",
            "created_at": "2015-05-07 14:15:00",
            "roles": [
                {
                    "role_id": 2,
                    "pivot": {
                        "user_id": 1,
                        "role_id": 2
                    }
                }
            ]
        },
        {
            "id": 2,
            "name": "bbbb",
            "password": "xxxxxxx",
            "created_at": "2015-05-05 14:15:00",
            "roles": [
                {
                    "role_id": 2,
                    "pivot": {
                        "user_id": 2,
                        "role_id": 2
                    }
                }
            ]
        },

But i do not want the password,created_at and pivot field. How to filter these?

Upvotes: 0

Views: 373

Answers (1)

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

To get relations you need to get the foreign keys. Try this

$query = User::with(['roles'=>function($q){
    $q->get(['id', 'name', 'slug']);
}])->get(['id','name', 'role_id']);

As for the pivot table, can you post you roles relation in the user model?

Edit Add this to your user model to hide the pivot properties

protected $hidden = ['pivot'];

You can add more fields to that property to remove them from all queries.

Upvotes: 0

Related Questions