Laravel Eloquent - Select 某些列与预先加载相结合

Laravel Eloquent - Select Certain Columns Combine with Eager Loading

如何 select 父级 table 的某些列,同时使用预先加载进行查询?

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

Return

[{"id":1,"username":"kuhn.desiree","email":"quentin.gleason@example.net","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"}}]

我只想要 usernameemail Account table。

您想添加一个 select 调用:

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

尝试使用此代码:

$accounts = \App\Account::with(['status' => function($q)
            {
                $q->select('username', 'email');
            }])->get();

一种方法是使用 select() 方法

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

如果您想检索包含单个列的值的集合,您可以使用 pluck 方法。:

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