Laravel中tosql()是如何返回sql

前言

1. laravel version 5.5 laravel

2. 關鍵字sql解析的代碼,我就不上了。有興趣的童鞋,能夠去Illuminate\Database\Query\Grammars\Grammar觀望,我也就簡單說下,Laravel的主體思路。sql

源碼

首先找到tosql()方法所在的位置,Illuminate\Database\Query\Builder:
/** * Get the SQL representation of the query. * * @return string */
    public function toSql() { return $this->grammar->compileSelect($this); }

接着,去 Illuminate\Database\Query\Grammars\Grammar數組

/**
     * The components that make up a select clause.
     *  關鍵字數組,用於下面的根據對應關鍵字拼接對應方法
     * @var array
     */
    protected $selectComponents = [
        'aggregate',
        'columns',
        'from',
        'joins',
        'wheres',
        'groups',
        'havings',
        'orders',
        'limit',
        'offset',
        'unions',
        'lock',
    ];

 

 /** * Compile a select query into SQL. * * @param \Illuminate\Database\Query\Builder $query * @return string */
    public function compileSelect(Builder $query) { // If the query does not have any columns set, we'll set the columns to the // * character to just get all of the columns from the database. Then we // can build the query and concatenate all the pieces together as one.
        $original = $query->columns; if (is_null($query->columns)) { $query->columns = ['*']; } // To compile the query, we'll spin through each component of the query and // see if that component exists. If it does we'll just call the compiler // function for the component which is responsible for making the SQL.
     // 然鵝,最主體的方法就在這裏。
$sql = trim($this->concatenate( $this->compileComponents($query)) ); $query->columns = $original; return $sql; }
    
 /** * Concatenate an array of segments, removing empties. * * @param array $segments * @return string */
    protected function concatenate($segments) {
     // 將空值過濾,而且轉換爲一個字符串,返回。(也就是最終返回的sql)
return implode(' ', array_filter($segments, function ($value) { return (string) $value !== ''; })); }
/** * Compile the components necessary for a select clause. * * @param \Illuminate\Database\Query\Builder $query * @return array */
    protected function compileComponents(Builder $query) { $sql = [];      // laravel 會根據sql的關鍵字,for循環出一個sql數組 foreach ($this->selectComponents as $component) { // To compile the query, we'll spin through each component of the query and // see if that component exists. If it does we'll just call the compiler // function for the component which is responsible for making the SQL.
            if (! is_null($query->$component)) { $method = 'compile'.ucfirst($component); $sql[$component] = $this->$method($query, $query->$component); } } return $sql;  }

 

總結

我我的也就是,簡略的經過表象的源碼分析下laravle的toSql()如何返回sql而已,還沒有研究更爲深透。源碼分析

爲何開個博文來記錄呢?由於,最近一直在看laravel的源碼,以爲這種思想真的很新穎!!!ui

共勉~~~this

相關文章
相關標籤/搜索