PHP头条
热点:

Laravel Eloquent ORM 时如何查询表中指定的字段


在使用Laravel ORM的Model方法find, get, first方法获取数据对象时返回的数据对象的attributes属性数组里会包含数据表中所有的字段对应的键值关系, 那么如何在ORM查询时只返回数据表中指定字段的数据呢?

很多时候,文档上没有写明的用法需要我们去看源码来探究的,下面我们就来看一下这三个方法的实现。

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

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

/** 
 * 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里如下:

/** 
 * 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方法查询返回指定的字段可通过如下四种方法来实现:

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

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

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

www.phpzy.comtrue/php/25360.htmlTechArticleLaravel Eloquent ORM 时如何查询表中指定的字段 在使用Laravel ORM的Model方法find, get, first方法获取数据对象时返回的数据对象的attributes属性数组里会包含数据表中所有的字段对应的键值关系,...

相关文章

PHP之友评论

今天推荐