雄辩的第一个where子句 [英] Eloquent the first where clause

查看:56
本文介绍了雄辩的第一个where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Laravel如何实现雄辩的语法,以便可以使用User::where()

I am wondering how Laravel implement eloquent syntax so that the first where clause can be called statically with User::where()

User::where('id', 23)->where('email', $email)->first();

它们是否具有public static function where()public function where()

推荐答案

在雄辩的模型上调用where确实涉及幕后发生的一些魔术.首先,以以下示例为例:

Calling where on an Eloquent model does involve a little bit of magic that occurs behind the scenes. Firstly, take the example of:

User::where(’name’, ‘Joe’)->first;

User类扩展的Model类上不存在静态where方法.

There’s no static where method that exists on the Model class that the User class extends.

发生的事情是,调用了PHP魔术方法__callStatic,该方法随后尝试调用where方法.

What happens, is that the PHP magic method __callStatic is called which attempts to then call the where method.

public static function __callStatic($method, $parameters)
{
    $instance = new static;

    return call_user_func_array([$instance, $method], $parameters);
}

由于没有名为where的明确定义的用户函数,因此将执行在Model中定义的下一个魔术PHP方法__call.

As there’s no explicitly defined user function called where, the next magic PHP method __call which is defined in Model is executed.

public function __call($method, $parameters)
{
    if (in_array($method, ['increment', 'decrement'])) {
        return call_user_func_array([$this, $method], $parameters);
    }

    $query = $this->newQuery();

    return call_user_func_array([$query, $method], $parameters);
}

可以通过以下方式访问与数据库相关的常用方法:

The common database related methods become accessible via:

$query = $this->newQuery();

这将实例化一个新的Eloquent查询构建器对象,并在该对象上运行where方法.

This instantiates a new Eloquent query builder object, and it’s on this object that the where method runs.

因此,当您使用```User :: where()``时,您实际上是在使用:

So, when you use ```User::where()`` you’re actually using:

Illuminate\Database\Eloquent\Builder::where()

看看 Builder类以查看全部您习惯使用的常见口才方法,例如where()get()first()update()等.

Take a look at the Builder class to see all of the common Eloquent methods you’re used to using, like where(), get(), first(), update(), etc.

Laracasts 上有一段很深入的(付费)视频,讲述了口才如何我建议在幕后工作.

Laracasts has a great in-depth (paid) video on how Eloquent works behind the scenes, which I recommend.

这篇关于雄辩的第一个where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆