whereType是laravel的什么用法?
Answer模型的代码
public function votes($type)
{
return $this->morphMany(Vote::class, 'voted')->whereType($type);
}
其中的whereType这是什么用法,我在文档中没有查到,希望有大佬能指点我一下。
谢谢。
先说结论:
whereColumn($value)
相当于where('column', '=', $value)
,例如问题中提到的whereType($type)
相当于where('type', '=', $type)
。这是Laravel
在背后为我们做的事情,今天不妨来debug
一番。首先,我们给
app/Models/Traits/VoteTrait.php
的votes()
方法简单修改下,并设置上断点:当我们到达第二个断点位置时,我们点击
step into
按钮:这个时候我们进入了
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php
的__call()
方法:__call() 方法是 PHP 提供的魔术方法之一:在对象中调用一个不可访问方法时,
__call()
会被调用。再次step into
:这下我们会进入
vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
:这里的
$object
是vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php
类的一个实例,所以我们会进入它的__call()
方法:我们再次
step into
:这里的
$object
是vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
类的一个实例,所以我们会进入它的__call()
方法:在这里我们可以看到,是通过
dynamicWhere()
方法来做的处理。我们进入该方法看下:进入
addDynamic()
方法:哈,原来是在这里做的处理,其他代码细节的部分就不说了。