普通查詢
查詢構造器
//使用select()
$users = DB::table('users')->select(['name', 'email as user_email'])->get();
//使用get()
$users = DB::table('users')->get(['name', 'email as user_email']);
Eloquent
//使用select()
$users = User::select(['name'])->get();
//直接將列名數組作為參數傳入all()/get()/find()等方法中
$users = User::all(['name']);
$admin_users = User::where('role', 'admin')->get(['id', 'name']);
$user = User::find($user_id, ['name']);
關聯模型
Model外
$posts = User::find($user_id)->posts()->select(['title'])->get();
$posts = User::find($user_id)->posts()->get(['title', 'description']);
model內
public function user()
{
return $this->hasOne('App\Model\User','user_id')->select('user_name', 'email');
}
注意這里不能使用動態屬性(->posts)來調用關聯關系,而需要使用關聯關系方法(->posts())。
引用
「使用laravel的Eloquent模型獲取數據庫的指定列」
申明
本文大部分摘選自引用部分,並對原文章進行了重新整理。