Laravel返回某一列字段

时间:2021-07-09
本文章向大家介绍Laravel返回某一列字段,主要包括Laravel返回某一列字段使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

普通查询

查询构造器

//使用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模型获取数据库的指定列」

「Laravel 5 的关联模型如何设置只查询部分字段」

申明

本文大部分摘选自引用部分,并对原文章进行了重新整理。

原文地址:https://www.cnblogs.com/luyuqiang/p/14990927.html