【问题标题】:Where clause in querybuilder and eloquentquerybuilder 中的 Where 子句和 eloquent
【发布时间】:2016-01-04 05:59:49
【问题描述】:

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

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

现在,问题是 whereUserId 是什么(虽然它很冗长,但语法让我感到困惑)以及我在 laravel 文档中的哪里可以找到它?

【问题讨论】:

    标签: php eloquent laravel-5.1 query-builder


    【解决方案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}()");
    }
    

    【讨论】:

    • 谢谢!当我阅读 dynamicWhere 方法时,我以为我明白了:D
    猜你喜欢
    • 2019-11-27
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多