您现在的位置是:网站首页> 编程资料编程资料

使用laravel的Eloquent模型如何获取数据库的指定列_php实例_

2023-05-25 314人已围观

简介 使用laravel的Eloquent模型如何获取数据库的指定列_php实例_

使用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模型如何获取数据库的指定列就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

-六神源码网