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

吾爱主题 阅读:120 2021-09-07 15:39:00 评论:0

在使用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

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容