嗯,这可能只是另一个(坏名)范围:
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}()");
}