1

How to select certain columns on parents table while querying with eager loading?

$accounts = \App\Account::with('status')->get();

Return

[{"id":1,"username":"kuhn.desiree","email":"[email protected]","last_login":"2009-04-02 23:21:20","created_at":"2017-07-15 19:07:03","updated_at":"2017-07-15 19:07:03","status_id":13,"status":{"id":13,"name":"ab","desc":"Quos quas.","created_at":"2017-07-15 19:07:01","updated_at":"2017-07-15 19:07:01"}}]

I only want username and email on Account table.

3 Answers 3

1

Try to use this code:

$accounts = \App\Account::with(['status' => function($q)
            {
                $q->select('username', 'email');
            }])->get();
Sign up to request clarification or add additional context in comments.

1 Comment

as far as I know this code only filter child table.
0

one way is using select() method

$accounts = \App\Account::with('status')->select('username', 'email','status_id')->get();

If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method.:

accounts = \App\Account::with('status')->pluck('username', 'email');

4 Comments

I have tried but unfortunately it returns null status. {"username":"kuhn.desiree","email":"quentin.gleason@example.‌​net","status":null}
@YosuaLijantoBinar check this select('username', 'email','status')
nice, please update your answer with $accounts = \App\Account::with('status')->select('username', 'email', 'status_id')->get(); and I will accept.
dude it needs status_id not status
0

You want to add a select call:

$accounts = \App\Account::with('status')->select('username', 'email')->get();

1 Comment

I have tried but unfortunately it returns null status. {"username":"kuhn.desiree","email":"[email protected]","status":null}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.