laravel的Eloquent模型獲取指定列


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

1. 使用select()

$users = User::select(['name'])->get();

2. 直接將列名數組作為參數傳入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']);

 

在關聯查詢中使用同理:

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

注意這里不能使用動態屬性(->posts)來調用關聯關系,而需要使用關聯關系方法(->posts())。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM