querybuilder中的Where子句和雄辩



我在下面看到了一些类似的代码:

public function scopeUserId($query, $user_id)
{
   return $query->whereUserId($user_id);
}

现在,问题是UserId属于什么(尽管它足够详细,但语法让我感到困惑),我在laravel文档中的哪里可以找到它?

好吧,这可能只是另一个(名称不正确)范围:

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)
}
...
}

Upd:确实如此。以下是相关的IlluminateDatabaseQueryBuilder类代码:

/**
 * 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}()");
}

最新更新