首頁 後端開發 php教程 辛星解读laravel源代码第一篇即Database的实现流程

辛星解读laravel源代码第一篇即Database的实现流程

Jun 23, 2016 pm 01:27 PM

     经过一天左右的努力,终于把laravel的源代码整合到了yaf框架上面,下面说一下laravel的db层的一些处理吧,我使用的是laravel5.1.4,下面是database所在的位置:laravel5.1.4/vendor/laravel/framework/src/Illuminate/Database ,这个路径就是它的文件地址目录。

     我们来到Database文件夹后,会看到一些目录,这里简单介绍下它们的作用:

      Connectors----用于连接  、    Console-----用于命令行  、    Eloquent-----用于ORM 

      Migrantions----用于迁移、      Query-------用于查询、       Schema--------用于操作数据库结构

     该目录下还有一些其他的文件,都是一些比较通用的文件和接口性质的东西,当然也有一些和MySQL以及Postgresql息息相关的东西,这里就不一一介绍啦。

      然后我们进入Query目录,发现它有两个目录和三个文件,其中Builder.php是具体的命令,比如我们常用的transaction、get、lists都是在这个文件中定义的,而Expression.php则是具体的表达式,而JoinClause.php则是和连接相关的操作,主要处理连接里面具体的每个小环节的操作。一般来说,这里面最大的就是Builder.php,它有52KB,它是负责接收用户传递过来的数据的,我们的命令也就写在这个接口里面。

        而Grammars文件夹则是根据用户的输入来进行编译,也就是它里面的函数多是以compile开头,而且多数是compileInsert这种形式,因为在它的源代码中我们经常会发现它的构造中是compile加上action的ucfirst操作之后的字符串拼接得到。而在Grammars里面又会有Grammar.php和MySqlGrammar.php等和具体的数据库相关的文件。

      而在Connection.php中引用它们的时候,它是不知道我们使用了哪个数据库的,因此laravel给我们提供的解决办法是,我不管你使用的是哪个具体的Grammar,我只知道,你给我用的时候,必须是QueryGrammar。由于我们的业务中都是使用的MySQL,因此我们可以写一个QueryGrammar来继承自MySQLGrammar,当然,不这样做也是可以的。

       其中绝大多数都是在Builder和Grammar中跳转,还有少数是需要Processor的,一般都是这样,很多具体的细节就不废话了。下面把Builder.php的代码贴上来把:

  

<?phpnamespace Illuminate\Database\Query;use Closure;use BadMethodCallException;use Illuminate\Support\Arr;use Illuminate\Support\Str;use InvalidArgumentException;use Illuminate\Support\Collection;use Illuminate\Pagination\Paginator;use Illuminate\Contracts\Support\Arrayable;use Illuminate\Database\ConnectionInterface;use Illuminate\Database\Query\Grammars\Grammar;use Illuminate\Pagination\LengthAwarePaginator;use Illuminate\Database\Query\Processors\Processor;class Builder{    /**     * The database connection instance.     *     * @var \Illuminate\Database\Connection     */    protected $connection;    /**     * The database query grammar instance.     *     * @var \Illuminate\Database\Query\Grammars\Grammar     */    protected $grammar;    /**     * The database query post processor instance.     *     * @var \Illuminate\Database\Query\Processors\Processor     */    protected $processor;    /**     * The current query value bindings.     *     * @var array     */    protected $bindings = [        'select' => [],        'join'   => [],        'where'  => [],        'having' => [],        'order'  => [],    ];    /**     * An aggregate function and column to be run.     *     * @var array     */    public $aggregate;    /**     * The columns that should be returned.     *     * @var array     */    public $columns;    /**     * Indicates if the query returns distinct results.     *     * @var bool     */    public $distinct = false;    /**     * The table which the query is targeting.     *     * @var string     */    public $from;    /**     * The table joins for the query.     *     * @var array     */    public $joins;    /**     * The where constraints for the query.     *     * @var array     */    public $wheres;    /**     * The groupings for the query.     *     * @var array     */    public $groups;    /**     * The having constraints for the query.     *     * @var array     */    public $havings;    /**     * The orderings for the query.     *     * @var array     */    public $orders;    /**     * The maximum number of records to return.     *     * @var int     */    public $limit;    /**     * The number of records to skip.     *     * @var int     */    public $offset;    /**     * The query union statements.     *     * @var array     */    public $unions;    /**     * The maximum number of union records to return.     *     * @var int     */    public $unionLimit;    /**     * The number of union records to skip.     *     * @var int     */    public $unionOffset;    /**     * The orderings for the union query.     *     * @var array     */    public $unionOrders;    /**     * Indicates whether row locking is being used.     *     * @var string|bool     */    public $lock;    /**     * The field backups currently in use.     *     * @var array     */    protected $backups = [];    /**     * All of the available clause operators.     *     * @var array     */    protected $operators = [        '=', '', '=', '', '!=',        'like', 'like binary', 'not like', 'between', 'ilike',        '&', '|', '^', '>',        'rlike', 'regexp', 'not regexp',        '~', '~*', '!~', '!~*', 'similar to',                'not similar to',    ];    /**     * Whether use write pdo for select.     *     * @var bool     */    protected $useWritePdo = false;    /**     * Create a new query builder instance.     *     * @param  \Illuminate\Database\ConnectionInterface  $connection     * @param  \Illuminate\Database\Query\Grammars\Grammar  $grammar     * @param  \Illuminate\Database\Query\Processors\Processor  $processor     * @return void     */    public function __construct(ConnectionInterface $connection,                                Grammar $grammar,                                Processor $processor)    {        $this->grammar = $grammar;        $this->processor = $processor;        $this->connection = $connection;    }    /**     * Set the columns to be selected.     *     * @param  array  $columns     * @return $this     */    public function select($columns = ['*'])    {        $this->columns = is_array($columns) ? $columns : func_get_args();        return $this;    }    /**     * Add a new "raw" select expression to the query.     *     * @param  string  $expression     * @param  array   $bindings     * @return \Illuminate\Database\Query\Builder|static     */    public function selectRaw($expression, array $bindings = [])    {        $this->addSelect(new Expression($expression));        if ($bindings) {            $this->addBinding($bindings, 'select');        }        return $this;    }    /**     * Add a subselect expression to the query.     *     * @param  \Closure|\Illuminate\Database\Query\Builder|string $query     * @param  string  $as     * @return \Illuminate\Database\Query\Builder|static     */    public function selectSub($query, $as)    {        if ($query instanceof Closure) {            $callback = $query;            $callback($query = $this->newQuery());        }        if ($query instanceof self) {            $bindings = $query->getBindings();            $query = $query->toSql();        } elseif (is_string($query)) {            $bindings = [];        } else {            throw new InvalidArgumentException;        }        return $this->selectRaw('('.$query.') as '.$this->grammar->wrap($as), $bindings);    }    /**     * Add a new select column to the query.     *     * @param  mixed  $column     * @return $this     */    public function addSelect($column)    {        $column = is_array($column) ? $column : func_get_args();        $this->columns = array_merge((array) $this->columns, $column);        return $this;    }    /**     * Force the query to only return distinct results.     *     * @return $this     */    public function distinct()    {        $this->distinct = true;        return $this;    }    /**     * Set the table which the query is targeting.     *     * @param  string  $table     * @return $this     */    public function from($table)    {        $this->from = $table;        return $this;    }    /**     * Add a join clause to the query.     *     * @param  string  $table     * @param  string  $one     * @param  string  $operator     * @param  string  $two     * @param  string  $type     * @param  bool    $where     * @return $this     */    public function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)    {        // If the first "column" of the join is really a Closure instance the developer        // is trying to build a join with a complex "on" clause containing more than        // one condition, so we'll add the join and call a Closure with the query.        if ($one instanceof Closure) {            $this->joins[] = new JoinClause($type, $table);            call_user_func($one, end($this->joins));        }        // If the column is simply a string, we can assume the join simply has a basic        // "on" clause with a single condition. So we will just build the join with        // this simple join clauses attached to it. There is not a join callback.        else {            $join = new JoinClause($type, $table);            $this->joins[] = $join->on(                $one, $operator, $two, 'and', $where            );        }        return $this;    }    /**     * Add a "join where" clause to the query.     *     * @param  string  $table     * @param  string  $one     * @param  string  $operator     * @param  string  $two     * @param  string  $type     * @return \Illuminate\Database\Query\Builder|static     */    public function joinWhere($table, $one, $operator, $two, $type = 'inner')    {        return $this->join($table, $one, $operator, $two, $type, true);    }    /**     * Add a left join to the query.     *     * @param  string  $table     * @param  string  $first     * @param  string  $operator     * @param  string  $second     * @return \Illuminate\Database\Query\Builder|static     */    public function leftJoin($table, $first, $operator = null, $second = null)    {        return $this->join($table, $first, $operator, $second, 'left');    }    /**     * Add a "join where" clause to the query.     *     * @param  string  $table     * @param  string  $one     * @param  string  $operator     * @param  string  $two     * @return \Illuminate\Database\Query\Builder|static     */    public function leftJoinWhere($table, $one, $operator, $two)    {        return $this->joinWhere($table, $one, $operator, $two, 'left');    }    /**     * Add a right join to the query.     *     * @param  string  $table     * @param  string  $first     * @param  string  $operator     * @param  string  $second     * @return \Illuminate\Database\Query\Builder|static     */    public function rightJoin($table, $first, $operator = null, $second = null)    {        return $this->join($table, $first, $operator, $second, 'right');    }    /**     * Add a "right join where" clause to the query.     *     * @param  string  $table     * @param  string  $one     * @param  string  $operator     * @param  string  $two     * @return \Illuminate\Database\Query\Builder|static     */    public function rightJoinWhere($table, $one, $operator, $two)    {        return $this->joinWhere($table, $one, $operator, $two, 'right');    }    /**     * Add a basic where clause to the query.     *     * @param  string|array|\Closure  $column     * @param  string  $operator     * @param  mixed   $value     * @param  string  $boolean     * @return $this     *     * @throws \InvalidArgumentException     */    public function where($column, $operator = null, $value = null, $boolean = 'and')    {        // If the column is an array, we will assume it is an array of key-value pairs        // and can add them each as a where clause. We will maintain the boolean we        // received when the method was called and pass it into the nested where.        if (is_array($column)) {            return $this->whereNested(function ($query) use ($column) {                foreach ($column as $key => $value) {                    $query->where($key, '=', $value);                }            }, $boolean);        }        // Here we will make some assumptions about the operator. If only 2 values are        // passed to the method, we will assume that the operator is an equals sign        // and keep going. Otherwise, we'll require the operator to be passed in.        if (func_num_args() == 2) {            list($value, $operator) = [$operator, '='];        } elseif ($this->invalidOperatorAndValue($operator, $value)) {            throw new InvalidArgumentException('Illegal operator and value combination.');        }        // If the columns is actually a Closure instance, we will assume the developer        // wants to begin a nested where statement which is wrapped in parenthesis.        // We'll add that Closure to the query then return back out immediately.        if ($column instanceof Closure) {            return $this->whereNested($column, $boolean);        }        // If the given operator is not found in the list of valid operators we will        // assume that the developer is just short-cutting the '=' operators and        // we will set the operators to '=' and set the values appropriately.        if (!in_array(strtolower($operator), $this->operators, true)) {            list($value, $operator) = [$operator, '='];        }        // If the value is a Closure, it means the developer is performing an entire        // sub-select within the query and we will need to compile the sub-select        // within the where clause to get the appropriate query record results.        if ($value instanceof Closure) {            return $this->whereSub($column, $operator, $value, $boolean);        }        // If the value is "null", we will just assume the developer wants to add a        // where null clause to the query. So, we will allow a short-cut here to        // that method for convenience so the developer doesn't have to check.        if (is_null($value)) {            return $this->whereNull($column, $boolean, $operator != '=');        }        // Now that we are working with just a simple query we can put the elements        // in our array and add the query binding to our array of bindings that        // will be bound to each SQL statements when it is finally executed.        $type = 'Basic';        $this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean');        if (!$value instanceof Expression) {            $this->addBinding($value, 'where');        }        return $this;    }    /**     * Add an "or where" clause to the query.     *     * @param  string  $column     * @param  string  $operator     * @param  mixed   $value     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhere($column, $operator = null, $value = null)    {        return $this->where($column, $operator, $value, 'or');    }    /**     * Determine if the given operator and value combination is legal.     *     * @param  string  $operator     * @param  mixed  $value     * @return bool     */    protected function invalidOperatorAndValue($operator, $value)    {        $isOperator = in_array($operator, $this->operators);        return $isOperator && $operator != '=' && is_null($value);    }    /**     * Add a raw where clause to the query.     *     * @param  string  $sql     * @param  array   $bindings     * @param  string  $boolean     * @return $this     */    public function whereRaw($sql, array $bindings = [], $boolean = 'and')    {        $type = 'raw';        $this->wheres[] = compact('type', 'sql', 'boolean');        $this->addBinding($bindings, 'where');        return $this;    }    /**     * Add a raw or where clause to the query.     *     * @param  string  $sql     * @param  array   $bindings     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereRaw($sql, array $bindings = [])    {        return $this->whereRaw($sql, $bindings, 'or');    }    /**     * Add a where between statement to the query.     *     * @param  string  $column     * @param  array   $values     * @param  string  $boolean     * @param  bool  $not     * @return $this     */    public function whereBetween($column, array $values, $boolean = 'and', $not = false)    {        $type = 'between';        $this->wheres[] = compact('column', 'type', 'boolean', 'not');        $this->addBinding($values, 'where');        return $this;    }    /**     * Add an or where between statement to the query.     *     * @param  string  $column     * @param  array   $values     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereBetween($column, array $values)    {        return $this->whereBetween($column, $values, 'or');    }    /**     * Add a where not between statement to the query.     *     * @param  string  $column     * @param  array   $values     * @param  string  $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereNotBetween($column, array $values, $boolean = 'and')    {        return $this->whereBetween($column, $values, $boolean, true);    }    /**     * Add an or where not between statement to the query.     *     * @param  string  $column     * @param  array   $values     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereNotBetween($column, array $values)    {        return $this->whereNotBetween($column, $values, 'or');    }    /**     * Add a nested where statement to the query.     *     * @param  \Closure $callback     * @param  string   $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereNested(Closure $callback, $boolean = 'and')    {        // To handle nested queries we'll actually create a brand new query instance        // and pass it off to the Closure that we have. The Closure can simply do        // do whatever it wants to a query then we will store it for compiling.        $query = $this->newQuery();        $query->from($this->from);        call_user_func($callback, $query);        return $this->addNestedWhereQuery($query, $boolean);    }    /**     * Add another query builder as a nested where to the query builder.     *     * @param  \Illuminate\Database\Query\Builder|static $query     * @param  string  $boolean     * @return $this     */    public function addNestedWhereQuery($query, $boolean = 'and')    {        if (count($query->wheres)) {            $type = 'Nested';            $this->wheres[] = compact('type', 'query', 'boolean');            $this->mergeBindings($query);        }        return $this;    }    /**     * Add a full sub-select to the query.     *     * @param  string   $column     * @param  string   $operator     * @param  \Closure $callback     * @param  string   $boolean     * @return $this     */    protected function whereSub($column, $operator, Closure $callback, $boolean)    {        $type = 'Sub';        $query = $this->newQuery();        // Once we have the query instance we can simply execute it so it can add all        // of the sub-select's conditions to itself, and then we can cache it off        // in the array of where clauses for the "main" parent query instance.        call_user_func($callback, $query);        $this->wheres[] = compact('type', 'column', 'operator', 'query', 'boolean');        $this->mergeBindings($query);        return $this;    }    /**     * Add an exists clause to the query.     *     * @param  \Closure $callback     * @param  string   $boolean     * @param  bool     $not     * @return $this     */    public function whereExists(Closure $callback, $boolean = 'and', $not = false)    {        $type = $not ? 'NotExists' : 'Exists';        $query = $this->newQuery();        // Similar to the sub-select clause, we will create a new query instance so        // the developer may cleanly specify the entire exists query and we will        // compile the whole thing in the grammar and insert it into the SQL.        call_user_func($callback, $query);        $this->wheres[] = compact('type', 'operator', 'query', 'boolean');        $this->mergeBindings($query);        return $this;    }    /**     * Add an or exists clause to the query.     *     * @param  \Closure $callback     * @param  bool     $not     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereExists(Closure $callback, $not = false)    {        return $this->whereExists($callback, 'or', $not);    }    /**     * Add a where not exists clause to the query.     *     * @param  \Closure $callback     * @param  string   $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereNotExists(Closure $callback, $boolean = 'and')    {        return $this->whereExists($callback, $boolean, true);    }    /**     * Add a where not exists clause to the query.     *     * @param  \Closure  $callback     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereNotExists(Closure $callback)    {        return $this->orWhereExists($callback, true);    }    /**     * Add a "where in" clause to the query.     *     * @param  string  $column     * @param  mixed   $values     * @param  string  $boolean     * @param  bool    $not     * @return $this     */    public function whereIn($column, $values, $boolean = 'and', $not = false)    {        $type = $not ? 'NotIn' : 'In';        // If the value of the where in clause is actually a Closure, we will assume that        // the developer is using a full sub-select for this "in" statement, and will        // execute those Closures, then we can re-construct the entire sub-selects.        if ($values instanceof Closure) {            return $this->whereInSub($column, $values, $boolean, $not);        }        if ($values instanceof Arrayable) {            $values = $values->toArray();        }        $this->wheres[] = compact('type', 'column', 'values', 'boolean');        $this->addBinding($values, 'where');        return $this;    }    /**     * Add an "or where in" clause to the query.     *     * @param  string  $column     * @param  mixed   $values     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereIn($column, $values)    {        return $this->whereIn($column, $values, 'or');    }    /**     * Add a "where not in" clause to the query.     *     * @param  string  $column     * @param  mixed   $values     * @param  string  $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereNotIn($column, $values, $boolean = 'and')    {        return $this->whereIn($column, $values, $boolean, true);    }    /**     * Add an "or where not in" clause to the query.     *     * @param  string  $column     * @param  mixed   $values     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereNotIn($column, $values)    {        return $this->whereNotIn($column, $values, 'or');    }    /**     * Add a where in with a sub-select to the query.     *     * @param  string   $column     * @param  \Closure $callback     * @param  string   $boolean     * @param  bool     $not     * @return $this     */    protected function whereInSub($column, Closure $callback, $boolean, $not)    {        $type = $not ? 'NotInSub' : 'InSub';        // To create the exists sub-select, we will actually create a query and call the        // provided callback with the query so the developer may set any of the query        // conditions they want for the in clause, then we'll put it in this array.        call_user_func($callback, $query = $this->newQuery());        $this->wheres[] = compact('type', 'column', 'query', 'boolean');        $this->mergeBindings($query);        return $this;    }    /**     * Add a "where null" clause to the query.     *     * @param  string  $column     * @param  string  $boolean     * @param  bool    $not     * @return $this     */    public function whereNull($column, $boolean = 'and', $not = false)    {        $type = $not ? 'NotNull' : 'Null';        $this->wheres[] = compact('type', 'column', 'boolean');        return $this;    }    /**     * Add an "or where null" clause to the query.     *     * @param  string  $column     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereNull($column)    {        return $this->whereNull($column, 'or');    }    /**     * Add a "where not null" clause to the query.     *     * @param  string  $column     * @param  string  $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereNotNull($column, $boolean = 'and')    {        return $this->whereNull($column, $boolean, true);    }    /**     * Add an "or where not null" clause to the query.     *     * @param  string  $column     * @return \Illuminate\Database\Query\Builder|static     */    public function orWhereNotNull($column)    {        return $this->whereNotNull($column, 'or');    }    /**     * Add a "where date" statement to the query.     *     * @param  string  $column     * @param  string   $operator     * @param  int   $value     * @param  string   $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereDate($column, $operator, $value, $boolean = 'and')    {        return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean);    }    /**     * Add a "where day" statement to the query.     *     * @param  string  $column     * @param  string   $operator     * @param  int   $value     * @param  string   $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereDay($column, $operator, $value, $boolean = 'and')    {        return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean);    }    /**     * Add a "where month" statement to the query.     *     * @param  string  $column     * @param  string   $operator     * @param  int   $value     * @param  string   $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereMonth($column, $operator, $value, $boolean = 'and')    {        return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean);    }    /**     * Add a "where year" statement to the query.     *     * @param  string  $column     * @param  string   $operator     * @param  int   $value     * @param  string   $boolean     * @return \Illuminate\Database\Query\Builder|static     */    public function whereYear($column, $operator, $value, $boolean = 'and')    {        return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean);    }    /**     * Add a date based (year, month, day) statement to the query.     *     * @param  string  $type     * @param  string  $column     * @param  string  $operator     * @param  int  $value     * @param  string  $boolean     * @return $this     */    protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and')    {        $this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value');        $this->addBinding($value, 'where');        return $this;    }    /**     * Handles dynamic "where" clauses to the query.     *     * @param  string  $method     * @param  string  $parameters     * @return $this     */    public function dynamicWhere($method, $parameters)    {        $finder = substr($method, 5);        $segments = preg_split('/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);        // The connector variable will determine which connector will be used for the        // query condition. We will change it as we come across new boolean values        // in the dynamic method strings, which could contain a number of these.        $connector = 'and';        $index = 0;        foreach ($segments as $segment) {            // If the segment is not a boolean connector, we can assume it is a column's name            // and we will add it to the query as a new constraint as a where clause, then            // we can keep iterating through the dynamic method string's segments again.            if ($segment != 'And' && $segment != 'Or') {                $this->addDynamic($segment, $connector, $parameters, $index);                $index++;            }            // Otherwise, we will store the connector so we know how the next where clause we            // find in the query should be connected to the previous ones, meaning we will            // have the proper boolean connector to connect the next where clause found.            else {                $connector = $segment;            }        }        return $this;    }    /**     * Add a single dynamic where clause statement to the query.     *     * @param  string  $segment     * @param  string  $connector     * @param  array   $parameters     * @param  int     $index     * @return void     */    protected function addDynamic($segment, $connector, $parameters, $index)    {        // Once we have parsed out the columns and formatted the boolean operators we        // are ready to add it to this query as a where clause just like any other        // clause on the query. Then we'll increment the parameter index values.        $bool = strtolower($connector);        $this->where(Str::snake($segment), '=', $parameters[$index], $bool);    }    /**     * Add a "group by" clause to the query.     *     * @param  array|string  $column,...     * @return $this     */    public function groupBy()    {        foreach (func_get_args() as $arg) {            $this->groups = array_merge((array) $this->groups, is_array($arg) ? $arg : [$arg]);        }        return $this;    }    /**     * Add a "having" clause to the query.     *     * @param  string  $column     * @param  string  $operator     * @param  string  $value     * @param  string  $boolean     * @return $this     */    public function having($column, $operator = null, $value = null, $boolean = 'and')    {        $type = 'basic';        $this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean');        if (!$value instanceof Expression) {            $this->addBinding($value, 'having');        }        return $this;    }    /**     * Add a "or having" clause to the query.     *     * @param  string  $column     * @param  string  $operator     * @param  string  $value     * @return \Illuminate\Database\Query\Builder|static     */    public function orHaving($column, $operator = null, $value = null)    {        return $this->having($column, $operator, $value, 'or');    }    /**     * Add a raw having clause to the query.     *     * @param  string  $sql     * @param  array   $bindings     * @param  string  $boolean     * @return $this     */    public function havingRaw($sql, array $bindings = [], $boolean = 'and')    {        $type = 'raw';        $this->havings[] = compact('type', 'sql', 'boolean');        $this->addBinding($bindings, 'having');        return $this;    }    /**     * Add a raw or having clause to the query.     *     * @param  string  $sql     * @param  array   $bindings     * @return \Illuminate\Database\Query\Builder|static     */    public function orHavingRaw($sql, array $bindings = [])    {        return $this->havingRaw($sql, $bindings, 'or');    }    /**     * Add an "order by" clause to the query.     *     * @param  string  $column     * @param  string  $direction     * @return $this     */    public function orderBy($column, $direction = 'asc')    {        $property = $this->unions ? 'unionOrders' : 'orders';        $direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';        $this->{$property}[] = compact('column', 'direction');        return $this;    }    /**     * Add an "order by" clause for a timestamp to the query.     *     * @param  string  $column     * @return \Illuminate\Database\Query\Builder|static     */    public function latest($column = 'created_at')    {        return $this->orderBy($column, 'desc');    }    /**     * Add an "order by" clause for a timestamp to the query.     *     * @param  string  $column     * @return \Illuminate\Database\Query\Builder|static     */    public function oldest($column = 'created_at')    {        return $this->orderBy($column, 'asc');    }    /**     * Add a raw "order by" clause to the query.     *     * @param  string  $sql     * @param  array  $bindings     * @return $this     */    public function orderByRaw($sql, $bindings = [])    {        $property = $this->unions ? 'unionOrders' : 'orders';        $type = 'raw';        $this->{$property}[] = compact('type', 'sql');        $this->addBinding($bindings, 'order');        return $this;    }    /**     * Set the "offset" value of the query.     *     * @param  int  $value     * @return $this     */    public function offset($value)    {        $property = $this->unions ? 'unionOffset' : 'offset';        $this->$property = max(0, $value);        return $this;    }    /**     * Alias to set the "offset" value of the query.     *     * @param  int  $value     * @return \Illuminate\Database\Query\Builder|static     */    public function skip($value)    {        return $this->offset($value);    }    /**     * Set the "limit" value of the query.     *     * @param  int  $value     * @return $this     */    public function limit($value)    {        $property = $this->unions ? 'unionLimit' : 'limit';        if ($value > 0) {            $this->$property = $value;        }        return $this;    }    /**     * Alias to set the "limit" value of the query.     *     * @param  int  $value     * @return \Illuminate\Database\Query\Builder|static     */    public function take($value)    {        return $this->limit($value);    }    /**     * Set the limit and offset for a given page.     *     * @param  int  $page     * @param  int  $perPage     * @return \Illuminate\Database\Query\Builder|static     */    public function forPage($page, $perPage = 15)    {        return $this->skip(($page - 1) * $perPage)->take($perPage);    }    /**     * Add a union statement to the query.     *     * @param  \Illuminate\Database\Query\Builder|\Closure  $query     * @param  bool  $all     * @return \Illuminate\Database\Query\Builder|static     */    public function union($query, $all = false)    {        if ($query instanceof Closure) {            call_user_func($query, $query = $this->newQuery());        }        $this->unions[] = compact('query', 'all');        return $this->mergeBindings($query);    }    /**     * Add a union all statement to the query.     *     * @param  \Illuminate\Database\Query\Builder|\Closure  $query     * @return \Illuminate\Database\Query\Builder|static     */    public function unionAll($query)    {        return $this->union($query, true);    }    /**     * Lock the selected rows in the table.     *     * @param  bool  $value     * @return $this     */    public function lock($value = true)    {        $this->lock = $value;        return $this;    }    /**     * Lock the selected rows in the table for updating.     *     * @return \Illuminate\Database\Query\Builder     */    public function lockForUpdate()    {        return $this->lock(true);    }    /**     * Share lock the selected rows in the table.     *     * @return \Illuminate\Database\Query\Builder     */    public function sharedLock()    {        return $this->lock(false);    }    /**     * Get the SQL representation of the query.     *     * @return string     */    public function toSql()    {        return $this->grammar->compileSelect($this);    }    /**     * Execute a query for a single record by ID.     *     * @param  int    $id     * @param  array  $columns     * @return mixed|static     */    public function find($id, $columns = ['*'])    {        return $this->where('id', '=', $id)->first($columns);    }    /**     * Get a single column's value from the first result of a query.     *     * @param  string  $column     * @return mixed     */    public function value($column)    {        $result = (array) $this->first([$column]);        return count($result) > 0 ? reset($result) : null;    }    /**     * Get a single column's value from the first result of a query.     *     * This is an alias for the "value" method.     *     * @param  string  $column     * @return mixed     *     * @deprecated since version 5.1.     */    public function pluck($column)    {        return $this->value($column);    }    /**     * Execute the query and get the first result.     *     * @param  array   $columns     * @return mixed|static     */    public function first($columns = ['*'])    {        $results = $this->take(1)->get($columns);        return count($results) > 0 ? reset($results) : null;    }    /**     * Execute the query as a "select" statement.     *     * @param  array  $columns     * @return array|static[]     */    public function get($columns = ['*'])    {        return $this->getFresh($columns);    }    /**     * Execute the query as a fresh "select" statement.     *     * @param  array  $columns     * @return array|static[]     */    public function getFresh($columns = ['*'])    {        if (is_null($this->columns)) {            $this->columns = $columns;        }        return $this->processor->processSelect($this, $this->runSelect());    }    /**     * Run the query as a "select" statement against the connection.     *     * @return array     */    protected function runSelect()    {        return $this->connection->select($this->toSql(), $this->getBindings(), !$this->useWritePdo);    }    /**     * Paginate the given query into a simple paginator.     *     * @param  int  $perPage     * @param  array  $columns     * @param  string  $pageName     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator     */    public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page')    {        $page = Paginator::resolveCurrentPage($pageName);        $total = $this->getCountForPagination($columns);        $results = $this->forPage($page, $perPage)->get($columns);        return new LengthAwarePaginator($results, $total, $perPage, $page, [            'path' => Paginator::resolveCurrentPath(),            'pageName' => $pageName,        ]);    }    /**     * Get a paginator only supporting simple next and previous links.     *     * This is more efficient on larger data-sets, etc.     *     * @param  int  $perPage     * @param  array  $columns     * @param  string  $pageName     * @return \Illuminate\Contracts\Pagination\Paginator     */    public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page')    {        $page = Paginator::resolveCurrentPage($pageName);        $this->skip(($page - 1) * $perPage)->take($perPage + 1);        return new Paginator($this->get($columns), $perPage, $page, [            'path' => Paginator::resolveCurrentPath(),            'pageName' => $pageName,        ]);    }    /**     * Get the count of the total records for the paginator.     *     * @param  array  $columns     * @return int     */    public function getCountForPagination($columns = ['*'])    {        $this->backupFieldsForCount();        $this->aggregate = ['function' => 'count', 'columns' => $columns];        $results = $this->get();        $this->aggregate = null;        $this->restoreFieldsForCount();        if (isset($this->groups)) {            return count($results);        }        return isset($results[0]) ? (int) array_change_key_case((array) $results[0])['aggregate'] : 0;    }    /**     * Backup some fields for the pagination count.     *     * @return void     */    protected function backupFieldsForCount()    {        foreach (['orders', 'limit', 'offset', 'columns'] as $field) {            $this->backups[$field] = $this->{$field};            $this->{$field} = null;        }    }    /**     * Restore some fields after the pagination count.     *     * @return void     */    protected function restoreFieldsForCount()    {        foreach (['orders', 'limit', 'offset', 'columns'] as $field) {            $this->{$field} = $this->backups[$field];        }        $this->backups = [];    }    /**     * Chunk the results of the query.     *     * @param  int  $count     * @param  callable  $callback     * @return void     */    public function chunk($count, callable $callback)    {        $results = $this->forPage($page = 1, $count)->get();        while (count($results) > 0) {            // On each chunk result set, we will pass them to the callback and then let the            // developer take care of everything within the callback, which allows us to            // keep the memory low for spinning through large result sets for working.            if (call_user_func($callback, $results) === false) {                break;            }            $page++;            $results = $this->forPage($page, $count)->get();        }    }    /**     * Get an array with the values of a given column.     *     * @param  string  $column     * @param  string  $key     * @return array     */    public function lists($column, $key = null)    {        $columns = $this->getListSelect($column, $key);        $results = new Collection($this->get($columns));        return $results->pluck($columns[0], Arr::get($columns, 1))->all();    }    /**     * Get the columns that should be used in a list array.     *     * @param  string  $column     * @param  string  $key     * @return array     */    protected function getListSelect($column, $key)    {        $select = is_null($key) ? [$column] : [$column, $key];        // If the selected column contains a "dot", we will remove it so that the list        // operation can run normally. Specifying the table is not needed, since we        // really want the names of the columns as it is in this resulting array.        return array_map(function ($column) {            $dot = strpos($column, '.');            return $dot === false ? $column : substr($column, $dot + 1);        }, $select);    }    /**     * Concatenate values of a given column as a string.     *     * @param  string  $column     * @param  string  $glue     * @return string     */    public function implode($column, $glue = null)    {        if (is_null($glue)) {            return implode($this->lists($column));        }        return implode($glue, $this->lists($column));    }    /**     * Determine if any rows exist for the current query.     *     * @return bool     */    public function exists()    {        $limit = $this->limit;        $result = $this->limit(1)->count() > 0;        $this->limit($limit);        return $result;    }    /**     * Retrieve the "count" result of the query.     *     * @param  string  $columns     * @return int     */    public function count($columns = '*')    {        if (!is_array($columns)) {            $columns = [$columns];        }        return (int) $this->aggregate(__FUNCTION__, $columns);    }    /**     * Retrieve the minimum value of a given column.     *     * @param  string  $column     * @return float|int     */    public function min($column)    {        return $this->aggregate(__FUNCTION__, [$column]);    }    /**     * Retrieve the maximum value of a given column.     *     * @param  string  $column     * @return float|int     */    public function max($column)    {        return $this->aggregate(__FUNCTION__, [$column]);    }    /**     * Retrieve the sum of the values of a given column.     *     * @param  string  $column     * @return float|int     */    public function sum($column)    {        $result = $this->aggregate(__FUNCTION__, [$column]);        return $result ?: 0;    }    /**     * Retrieve the average of the values of a given column.     *     * @param  string  $column     * @return float|int     */    public function avg($column)    {        return $this->aggregate(__FUNCTION__, [$column]);    }    /**     * Execute an aggregate function on the database.     *     * @param  string  $function     * @param  array   $columns     * @return float|int     */    public function aggregate($function, $columns = ['*'])    {        $this->aggregate = compact('function', 'columns');        $previousColumns = $this->columns;        $results = $this->get($columns);        // Once we have executed the query, we will reset the aggregate property so        // that more select queries can be executed against the database without        // the aggregate value getting in the way when the grammar builds it.        $this->aggregate = null;        $this->columns = $previousColumns;        if (isset($results[0])) {            $result = array_change_key_case((array) $results[0]);            return $result['aggregate'];        }    }    /**     * Insert a new record into the database.     *     * @param  array  $values     * @return bool     */    public function insert(array $values)    {        if (empty($values)) {            return true;        }        // Since every insert gets treated like a batch insert, we will make sure the        // bindings are structured in a way that is convenient for building these        // inserts statements by verifying the elements are actually an array.        if (!is_array(reset($values))) {            $values = [$values];        }        // Since every insert gets treated like a batch insert, we will make sure the        // bindings are structured in a way that is convenient for building these        // inserts statements by verifying the elements are actually an array.        else {            foreach ($values as $key => $value) {                ksort($value);                $values[$key] = $value;            }        }        // We'll treat every insert like a batch insert so we can easily insert each        // of the records into the database consistently. This will make it much        // easier on the grammars to just handle one type of record insertion.        $bindings = [];        foreach ($values as $record) {            foreach ($record as $value) {                $bindings[] = $value;            }        }        $sql = $this->grammar->compileInsert($this, $values);        // Once we have compiled the insert statement's SQL we can execute it on the        // connection and return a result as a boolean success indicator as that        // is the same type of result returned by the raw connection instance.        $bindings = $this->cleanBindings($bindings);        return $this->connection->insert($sql, $bindings);    }    /**     * Insert a new record and get the value of the primary key.     *     * @param  array   $values     * @param  string  $sequence     * @return int     */    public function insertGetId(array $values, $sequence = null)    {        $sql = $this->grammar->compileInsertGetId($this, $values, $sequence);        $values = $this->cleanBindings($values);        return $this->processor->processInsertGetId($this, $sql, $values, $sequence);    }    /**     * Update a record in the database.     *     * @param  array  $values     * @return int     */    public function update(array $values)    {        $bindings = array_values(array_merge($values, $this->getBindings()));        $sql = $this->grammar->compileUpdate($this, $values);        return $this->connection->update($sql, $this->cleanBindings($bindings));    }    /**     * Increment a column's value by a given amount.     *     * @param  string  $column     * @param  int     $amount     * @param  array   $extra     * @return int     */    public function increment($column, $amount = 1, array $extra = [])    {        $wrapped = $this->grammar->wrap($column);        $columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);        return $this->update($columns);    }    /**     * Decrement a column's value by a given amount.     *     * @param  string  $column     * @param  int     $amount     * @param  array   $extra     * @return int     */    public function decrement($column, $amount = 1, array $extra = [])    {        $wrapped = $this->grammar->wrap($column);        $columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra);        return $this->update($columns);    }    /**     * Delete a record from the database.     *     * @param  mixed  $id     * @return int     */    public function delete($id = null)    {        // If an ID is passed to the method, we will set the where clause to check        // the ID to allow developers to simply and quickly remove a single row        // from their database without manually specifying the where clauses.        if (!is_null($id)) {            $this->where('id', '=', $id);        }        $sql = $this->grammar->compileDelete($this);        return $this->connection->delete($sql, $this->getBindings());    }    /**     * Run a truncate statement on the table.     *     * @return void     */    public function truncate()    {        foreach ($this->grammar->compileTruncate($this) as $sql => $bindings) {            $this->connection->statement($sql, $bindings);        }    }    /**     * Get a new instance of the query builder.     *     * @return \Illuminate\Database\Query\Builder     */    public function newQuery()    {        return new static($this->connection, $this->grammar, $this->processor);    }    /**     * Merge an array of where clauses and bindings.     *     * @param  array  $wheres     * @param  array  $bindings     * @return void     */    public function mergeWheres($wheres, $bindings)    {        $this->wheres = array_merge((array) $this->wheres, (array) $wheres);        $this->bindings['where'] = array_values(array_merge($this->bindings['where'], (array) $bindings));    }    /**     * Remove all of the expressions from a list of bindings.     *     * @param  array  $bindings     * @return array     */    protected function cleanBindings(array $bindings)    {        return array_values(array_filter($bindings, function ($binding) {            return !$binding instanceof Expression;        }));    }    /**     * Create a raw database expression.     *     * @param  mixed  $value     * @return \Illuminate\Database\Query\Expression     */    public function raw($value)    {        return $this->connection->raw($value);    }    /**     * Get the current query value bindings in a flattened array.     *     * @return array     */    public function getBindings()    {        return Arr::flatten($this->bindings);    }    /**     * Get the raw array of bindings.     *     * @return array     */    public function getRawBindings()    {        return $this->bindings;    }    /**     * Set the bindings on the query builder.     *     * @param  array   $bindings     * @param  string  $type     * @return $this     *     * @throws \InvalidArgumentException     */    public function setBindings(array $bindings, $type = 'where')    {        if (!array_key_exists($type, $this->bindings)) {            throw new InvalidArgumentException("Invalid binding type: {$type}.");        }        $this->bindings[$type] = $bindings;        return $this;    }    /**     * Add a binding to the query.     *     * @param  mixed   $value     * @param  string  $type     * @return $this     *     * @throws \InvalidArgumentException     */    public function addBinding($value, $type = 'where')    {        if (!array_key_exists($type, $this->bindings)) {            throw new InvalidArgumentException("Invalid binding type: {$type}.");        }        if (is_array($value)) {            $this->bindings[$type] = array_values(array_merge($this->bindings[$type], $value));        } else {            $this->bindings[$type][] = $value;        }        return $this;    }    /**     * Merge an array of bindings into our bindings.     *     * @param  \Illuminate\Database\Query\Builder  $query     * @return $this     */    public function mergeBindings(Builder $query)    {        $this->bindings = array_merge_recursive($this->bindings, $query->bindings);        return $this;    }    /**     * Get the database connection instance.     *     * @return \Illuminate\Database\ConnectionInterface     */    public function getConnection()    {        return $this->connection;    }    /**     * Get the database query processor instance.     *     * @return \Illuminate\Database\Query\Processors\Processor     */    public function getProcessor()    {        return $this->processor;    }    /**     * Get the query grammar instance.     *     * @return \Illuminate\Database\Query\Grammars\Grammar     */    public function getGrammar()    {        return $this->grammar;    }    /**     * Use the write pdo for query.     *     * @return $this     */    public function useWritePdo()    {        $this->useWritePdo = true;        return $this;    }    /**     * Handle dynamic method calls into the method.     *     * @param  string  $method     * @param  array   $parameters     * @return mixed     *     * @throws \BadMethodCallException     */    public function __call($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}()");    }}
登入後複製


版权声明:本文为博主原创文章,未经博主允许不得转载。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1318
25
PHP教程
1269
29
C# 教程
1248
24
PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? 說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? Apr 17, 2025 am 12:06 AM

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP與Python:了解差異 PHP與Python:了解差異 Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

See all articles