first() 但在IlluminateDatabaseEloquentModel中却找不到where方法。不过在555行找到了使用where的代码: {代码...} 这里的static::where()是怎么..."/> first() 但在IlluminateDatabaseEloquentModel中却找不到where方法。不过在555行找到了使用where的代码: {代码...} 这里的static::where()是怎么...">

Laravel 中static方法为什么在相应的类中找不到

WBOY
Release: 2016-06-06 20:39:09
Original
1101 people have browsed it

有一个名称为Shop的model,可以使用Shop::where("id",14)->first()
但在Illuminate\Database\Eloquent\Model中却找不到where方法。不过在555行找到了使用where的代码:

<code>if ( ! is_null($instance = static::where($attributes)->first()))
{
    return $instance;
}
</code>
Copy after login
Copy after login

这里的static::where()是怎么回事,Shop::where()是调用的哪里的where方法

回复内容:

有一个名称为Shop的model,可以使用Shop::where("id",14)->first()
但在Illuminate\Database\Eloquent\Model中却找不到where方法。不过在555行找到了使用where的代码:

<code>if ( ! is_null($instance = static::where($attributes)->first()))
{
    return $instance;
}
</code>
Copy after login
Copy after login

这里的static::where()是怎么回事,Shop::where()是调用的哪里的where方法

看这一行代码
https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L3354

<code>php</code><code>public static function __callStatic($method, $parameters)
{
    $instance = new static;
    return call_user_func_array(array($instance, $method), $parameters);
}
</code>
Copy after login

意思是如果静态方法找不到,会尝试实例化之后再次调用对象方法

<code>Model::where()到这里会变成$model->where()
</code>
Copy after login

再继续看
https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L3335
这行代码

<code>php</code><code>public 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);
}
</code>
Copy after login

意思是如果本身再没有->where()这个方法,会再次尝试实例化一个\Illuminate\Database\Eloquent\Builder对象并填充当前已经设置过的一些参数,再进行操作

<code>到这里Model::where()会变成 $model->newQuery()->where()
</code>
Copy after login

所以到最后,你调用到的是

<code>php</code><code>new \Illuminate\Database\Eloquent\Builder()->where()
</code>
Copy after login

这个方法

<code>vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php#384-457
</code>
Copy after login

补充:http://v4.golaravel.com/docs/4.2/facades

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template