- /**
- * 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']);
在不同的场景下三者中选符合需要的使用即可。