Laravel Eloquent ORM 实现查询表中指定的字段

2019-11-0707:49:06后端程序开发Comments6,171 views字数 1406阅读模式

使用Laravel ORM的Model方法find, get, first方法获取数据对象时返回的数据对象的attributes属性数组里会包含数据表中所有的字段对应的键值关系, 那么如何在ORM查询时只返回数据表中指定字段的数据呢?很多时候,文档上没有写明的用法需要我们去看源码来探究的,下面我们就来看一下这三个方法的实现。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/17391.html

由于ORM依赖了QueryBuilder来实现查询, 在QueryBuilder的源码里通过查看get,first方法的实现可以到,他们都可以接收一个数组参数来指定要查询的字段:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/17391.html

find方法的实现是在\Illuminate\Database\Eloquent\Builder类里,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/17391.html

/** 
 * Find a model by its primary key. 
 * 
 * @param mixed $id 
 * @param array $columns 
 * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null 
 */ 
public function find($id, $columns = ['*']) 
{ 
 if (is_array($id)) { 
  return $this->findMany($id, $columns); 
 } 
 
 $this->query->where($this->model->getQualifiedKeyName(), '=', $id); 
 
 return $this->first($columns); 
}

由于Eloquent Query Builder是依赖查询构建器\Illuminate\Database\Query\Builder的,first和get方法的源码在Query Builder里如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/17391.html

/** 
 * Execute the query and get the first result. 
 * 
 * @param array $columns 
 * @return mixed|static 
 */ 
public function first($columns = ['*']) 
{ 
 $results = $this->take(1)->get($columns); 
 
 return count($results) > 0 ? reset($results) : null; 
} 
 
/** 
 * Execute the query as a "select" statement. 
 * 
 * @param array $columns 
 * @return array|static[] 
 */ 
public function get($columns = ['*']) 
{ 
 if (is_null($this->columns)) { 
  $this->columns = $columns; 
 } 
 
 return $this->processor->processSelect($this, $this->runSelect()); 
}

所以使用Laravel的ORM方法查询返回指定的字段可通过如下三种方法来实现文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/17391.html

$data = ModelA::find($id, ['column1', 'column2']); 
 
$data = ModelA::first(['column1', 'column2']); 
 
$data = ModelA::where(['column1', '=', 'value'])->get(['column1', 'column2']);

在不同的场景下三者中选符合需要的使用即可。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/17391.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/17391.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定