1. 程式人生 > >使用laravel的Eloquent模型獲取資料庫的指定列

使用laravel的Eloquent模型獲取資料庫的指定列

使用Laravel的ORM——Eloquent時,時常遇到的一個操作是取模型中的其中一些屬性,對應的就是在資料庫中取表的特定列。

如果使用DB門面寫查詢構造器,那隻需要鏈式呼叫select()方法即可:

$users = DB::table('users')->select('name', 'email as user_email')->get();

使用Eloquent的話,有兩種方式:

  1. 使用select()
$users = User::select(['name'])->get();
$users = User::select
('name')->get();
  1. 直接將列名陣列作為引數傳入all()/get()/find()等方法中
1 $users = User::all(['name']);
2 $admin_users = User::where('role', 'admin')->get(['id', 'name']);
3 $user = User::find($user_id, ['name']);
4 $user = User::where('role', 'admin')->first(['name']);

在關聯查詢中使用同理:

$posts = User::find($user_id)
->
posts()->select(['title'])->get(); $posts = User::find($user_id)->posts()->get(['title', 'description']);

注意這裡不能使用動態屬性(->posts)來呼叫關聯關係,而需要使用關聯關係方法(->posts())。