導讀:在使用Laravel ORM的Model方法find, get, first方法獲取數據對象時返回的數據對象的attributes屬性數組裏會包含數據表中所有的字段對應...原文地址:http://www.bcty365.com/content-153-5939-1.html
在使用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']);
在不同的場景下三者中選符合需要的使用即可。