服务器之家

服务器之家 > 正文

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

时间:2021-09-07 15:39     来源/作者:b5教程网

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

由于ORM依赖了QueryBuilder来实现查询, 在QueryBuilder的源码里通过查看get,first方法的实现可以到,他们都可以接收一个数组参数来指定要查询的字段:

find方法的实现是在\Illuminate\Database\Eloquent\Builder类里,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * Find a model by its primary key.
 *www.bcty365.com
 * @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里如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * 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方法查询返回指定的字段可通过如下三种方法来实现

?
1
2
3
4
5
$data = ModelA::find($id, ['column1', 'column2']);
 
$data = ModelA::first(['column1', 'column2']);
 
$data = ModelA::where(['column1', '=', 'value'])->get(['column1', 'column2']);

在不同的场景下三者中选符合需要的使用即可。

以上这篇Laravel Eloquent ORM 实现查询表中指定的字段就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.bcty365.com/content-153-5939-1.html

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部