我见过这样的代码如下:
public function scopeUserId($query, $user_id)
{
return $query->whereUserId($user_id);
}
现在,问题是whereUserId属于什么(虽然它足够冗长,但语法让我感到困惑)我在哪里可以找到laravel文档?
答案 0 :(得分:1)
嗯,这可能只是另一个(命名不好的)范围:
public function scopeWhereUserId($query, $user_id) {
return $query->where("user_id", $user_id);
}
public function scopeUserId($query, $user_id) {
return $query->whereUserId($user_id);
}
...
$roles = Roles::whereUserId($id);
$roles_flattened = Roles::userId($id)->flatten();
...或者是查询构建器的一些魔术扩展替换(或者它是内置构建器吗?):
class MyQueryBuilder extends QueryBuilder {
...
public function __call($method, $args) {
if (Str::beginsWith($method, "where")) {
$whereColumn = str_replace("where", "", $method);
$whereColumn = camelCaseToSnakeCase($whereColumn);
return $this->where($whereColumn, array_shift($args))
}
return parent::__call($method, $args)
}
...
}
更新:确实如此。以下是相关的Illuminate\Database\Query\Builder
类代码:
/**
* Handle dynamic method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if (Str::startsWith($method, 'where')) {
return $this->dynamicWhere($method, $parameters);
}
$className = get_class($this);
throw new BadMethodCallException("Call to undefined method {$className}::{$method}()");
}