无为清净楼资源网 Design By www.qnjia.com

使用Laravel的ORM——Eloquent时,时常遇到的一个操作是取模型中的其中一些属性,对应的就是在数据库中取表的特定列。

如果使用DB门面写查询构造器,那只需要链式调用select()方法即可:

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

使用Eloquent的话,有两种方式:

使用select()

$users = User::select(['name'])->get();
$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']);
$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())。

以上这篇使用laravel的Eloquent模型如何获取数据库的指定列就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
laravel,Eloquent,数据库,指定列

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com