使用Laravel的ORM——Eloquent時,時常遇到的一個操做是取模型中的其中一些屬性,對應的就是在數據庫中取表的特定列。html
若是使用DB門面寫查詢構造器,那隻須要鏈式調用select()方法便可:laravel
$users = DB::table('users')->select('name', 'email as user_email')->get();
使用Eloquent的話,有兩種方式:數據庫
1. 使用select()數組
$users = User::select(['name'])->get();
2. 直接將列名數組做爲參數傳入all()/get()/find()等方法中post
1 $users = User::all(['name']); 2 $admin_users = User::where('role', 'admin')->get(['id', 'name']); 3 $user = User::find($user_id, ['name']);
在關聯查詢中使用同理:url
$posts = User::find($user_id)->posts()->select(['title'])->get();
$posts = User::find($user_id)->posts()->get(['title', 'description']);
注意這裏不能使用動態屬性(->posts)來調用關聯關係,而須要使用關聯關係方法(->posts())。code