有一個名稱為Shop的model,可以使用
Shop::where("id",14)->first()
但在
Illuminate\Database\Eloquent\Model中卻找不到where方法。不過在555行找到了使用
where的代碼:
if ( ! is_null($instance = static::where($attributes)->first())){ return $instance;}
這裡的static::where()是怎麼回事,Shop::where()是調用的哪裡的where方法
回複內容:
有一個名稱為Shop的model,可以使用Shop::where("id",14)->first()
但在Illuminate\Database\Eloquent\Model中卻找不到where方法。不過在555行找到了使用where的代碼:
if ( ! is_null($instance = static::where($attributes)->first())){ return $instance;}
這裡的static::where()是怎麼回事,Shop::where()是調用的哪裡的where方法
看這一行代碼
https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L3354
phppublic static function __callStatic($method, $parameters){ $instance = new static; return call_user_func_array(array($instance, $method), $parameters);}
意思是如果靜態方法找不到,會嘗試執行個體化之後再次調用對象方法
Model::where()到這裡會變成$model->where()
再繼續看
https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L3335
這行代碼
phppublic function __call($method, $parameters){ if (in_array($method, array('increment', 'decrement'))) { return call_user_func_array(array($this, $method), $parameters); } $query = $this->newQuery(); return call_user_func_array(array($query, $method), $parameters);}
意思是如果本身再沒有->where()這個方法,會再次嘗試執行個體化一個\Illuminate\Database\Eloquent\Builder對象並填充當前已經設定過的一些參數,再進行操作
到這裡Model::where()會變成 $model->newQuery()->where()
所以到最後,你調用到的是
phpnew \Illuminate\Database\Eloquent\Builder()->where()
這個方法
vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php#384-457
補充:http://v4.golaravel.com/docs/4.2/facades