有一个名称为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