如何在使用预先加载查询时选择父表上的某些列?
$accounts = \App\Account::with('status')->get();
返回
[{"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"}}]
我只希望username
表上有email
和Account
。
答案 0 :(得分:1)
尝试使用此代码:
$accounts = \App\Account::with(['status' => function($q)
{
$q->select('username', 'email');
}])->get();
答案 1 :(得分:0)
您想添加一个选择呼叫:
$accounts = \App\Account::with('status')->select('username', 'email')->get();
答案 2 :(得分:0)
一种方法是使用select()
方法
$accounts = \App\Account::with('status')->select('username', 'email','status_id')->get();
如果要检索包含单个列值的Collection,可以使用pluck方法。:
accounts = \App\Account::with('status')->pluck('username', 'email');